1 /* $NetBSD: bn_mp_reduce_2k.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */ 2 3 #include <tommath.h> 4 #ifdef BN_MP_REDUCE_2K_C 5 /* LibTomMath, multiple-precision integer library -- Tom St Denis 6 * 7 * LibTomMath is a library that provides multiple-precision 8 * integer arithmetic as well as number theoretic functionality. 9 * 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. 13 * 14 * The library is free for all purposes without any express 15 * guarantee it works. 16 * 17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org 18 */ 19 20 /* reduces a modulo n where n is of the form 2**p - d */ 21 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d) 22 { 23 mp_int q; 24 int p, res; 25 26 if ((res = mp_init(&q)) != MP_OKAY) { 27 return res; 28 } 29 30 p = mp_count_bits(n); 31 top: 32 /* q = a/2**p, a = a mod 2**p */ 33 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) { 34 goto ERR; 35 } 36 37 if (d != 1) { 38 /* q = q * d */ 39 if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) { 40 goto ERR; 41 } 42 } 43 44 /* a = a + q */ 45 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) { 46 goto ERR; 47 } 48 49 if (mp_cmp_mag(a, n) != MP_LT) { 50 s_mp_sub(a, n, a); 51 goto top; 52 } 53 54 ERR: 55 mp_clear(&q); 56 return res; 57 } 58 59 #endif 60 61 /* Source: /cvs/libtom/libtommath/bn_mp_reduce_2k.c,v */ 62 /* Revision: 1.4 */ 63 /* Date: 2006/12/28 01:25:13 */ 64