1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is library that provides for multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library is designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
17 /* Greatest Common Divisor using the binary method [Algorithm B, page 338, vol2 of TAOCP]
20 mp_gcd (mp_int * a, mp_int * b, mp_int * c)
25 /* either zero than gcd is the largest */
26 if (mp_iszero (a) == 1 && mp_iszero (b) == 0) {
27 return mp_copy (b, c);
29 if (mp_iszero (a) == 0 && mp_iszero (b) == 1) {
30 return mp_copy (a, c);
32 if (mp_iszero (a) == 1 && mp_iszero (b) == 1) {
37 /* if both are negative they share (-1) as a common divisor */
38 neg = (a->sign == b->sign) ? a->sign : MP_ZPOS;
40 if ((res = mp_init_copy (&u, a)) != MP_OKAY) {
44 if ((res = mp_init_copy (&v, b)) != MP_OKAY) {
48 /* must be positive for the remainder of the algorithm */
49 u.sign = v.sign = MP_ZPOS;
51 if ((res = mp_init (&t)) != MP_OKAY) {
55 /* B1. Find power of two */
57 while (mp_iseven(&u) == 1 && mp_iseven(&v) == 1) {
59 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
62 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
68 if (mp_isodd(&u) == 1) {
70 if ((res = mp_copy (&v, &t)) != MP_OKAY) {
76 if ((res = mp_copy (&u, &t)) != MP_OKAY) {
82 /* B3 (and B4). Halve t, if even */
83 while (t.used != 0 && mp_iseven(&t) == 1) {
84 if ((res = mp_div_2 (&t, &t)) != MP_OKAY) {
89 /* B5. if t>0 then u=t otherwise v=-t */
90 if (t.used != 0 && t.sign != MP_NEG) {
91 if ((res = mp_copy (&t, &u)) != MP_OKAY) {
95 if ((res = mp_copy (&t, &v)) != MP_OKAY) {
98 v.sign = (v.sign == MP_ZPOS) ? MP_NEG : MP_ZPOS;
101 /* B6. t = u - v, if t != 0 loop otherwise terminate */
102 if ((res = mp_sub (&u, &v, &t)) != MP_OKAY) {
105 } while (mp_iszero(&t) == 0);
107 /* multiply by 2^k which we divided out at the beginning */
108 if ((res = mp_mul_2d (&u, k, &u)) != MP_OKAY) {