1 /* $NetBSD: bn_mp_gcd.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
7 * LibTomMath is a library that provides multiple-precision
8 * integer arithmetic as well as number theoretic functionality.
10 * The library was designed directly after the MPI library by
11 * Michael Fromberger but has been written from scratch with
12 * additional optimizations in place.
14 * The library is free for all purposes without any express
17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
20 /* Greatest Common Divisor using the binary method */
21 int mp_gcd (mp_int
* a
, mp_int
* b
, mp_int
* c
)
24 int k
, u_lsb
, v_lsb
, res
;
26 /* either zero than gcd is the largest */
27 if (mp_iszero (a
) == MP_YES
) {
30 if (mp_iszero (b
) == MP_YES
) {
34 /* get copies of a and b we can modify */
35 if ((res
= mp_init_copy (&u
, a
)) != MP_OKAY
) {
39 if ((res
= mp_init_copy (&v
, b
)) != MP_OKAY
) {
43 /* must be positive for the remainder of the algorithm */
44 u
.sign
= v
.sign
= MP_ZPOS
;
46 /* B1. Find the common power of two for u and v */
47 u_lsb
= mp_cnt_lsb(&u
);
48 v_lsb
= mp_cnt_lsb(&v
);
49 k
= MIN(u_lsb
, v_lsb
);
52 /* divide the power of two out */
53 if ((res
= mp_div_2d(&u
, k
, &u
, NULL
)) != MP_OKAY
) {
57 if ((res
= mp_div_2d(&v
, k
, &v
, NULL
)) != MP_OKAY
) {
62 /* divide any remaining factors of two out */
64 if ((res
= mp_div_2d(&u
, u_lsb
- k
, &u
, NULL
)) != MP_OKAY
) {
70 if ((res
= mp_div_2d(&v
, v_lsb
- k
, &v
, NULL
)) != MP_OKAY
) {
75 while (mp_iszero(&v
) == 0) {
76 /* make sure v is the largest */
77 if (mp_cmp_mag(&u
, &v
) == MP_GT
) {
78 /* swap u and v to make sure v is >= u */
82 /* subtract smallest from largest */
83 if ((res
= s_mp_sub(&v
, &u
, &v
)) != MP_OKAY
) {
87 /* Divide out all factors of two */
88 if ((res
= mp_div_2d(&v
, mp_cnt_lsb(&v
), &v
, NULL
)) != MP_OKAY
) {
93 /* multiply by 2**k which we divided out at the beginning */
94 if ((res
= mp_mul_2d (&u
, k
, c
)) != MP_OKAY
) {
105 /* Source: /cvs/libtom/libtommath/bn_mp_gcd.c,v */
107 /* Date: 2006/12/28 01:25:13 */