3 /* LibTomMath, multiple-precision integer library -- Tom St Denis
5 * LibTomMath is a library that provides multiple-precision
6 * integer arithmetic as well as number theoretic functionality.
8 * The library was designed directly after the MPI library by
9 * Michael Fromberger but has been written from scratch with
10 * additional optimizations in place.
12 * The library is free for all purposes without any express
15 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
18 /* Greatest Common Divisor using the binary method */
19 int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
22 int k, u_lsb, v_lsb, res;
24 /* either zero than gcd is the largest */
25 if (mp_iszero (a) == 1 && mp_iszero (b) == 0) {
28 if (mp_iszero (a) == 0 && mp_iszero (b) == 1) {
32 /* optimized. At this point if a == 0 then
33 * b must equal zero too
35 if (mp_iszero (a) == 1) {
40 /* get copies of a and b we can modify */
41 if ((res = mp_init_copy (&u, a)) != MP_OKAY) {
45 if ((res = mp_init_copy (&v, b)) != MP_OKAY) {
49 /* must be positive for the remainder of the algorithm */
50 u.sign = v.sign = MP_ZPOS;
52 /* B1. Find the common power of two for u and v */
53 u_lsb = mp_cnt_lsb(&u);
54 v_lsb = mp_cnt_lsb(&v);
55 k = MIN(u_lsb, v_lsb);
58 /* divide the power of two out */
59 if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
63 if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
68 /* divide any remaining factors of two out */
70 if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
76 if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
81 while (mp_iszero(&v) == 0) {
82 /* make sure v is the largest */
83 if (mp_cmp_mag(&u, &v) == MP_GT) {
84 /* swap u and v to make sure v is >= u */
88 /* subtract smallest from largest */
89 if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
93 /* Divide out all factors of two */
94 if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
99 /* multiply by 2**k which we divided out at the beginning */
100 if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) {