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@gmail.com, http://libtom.org
18
/* reduces x mod m, assumes 0 < x < m**2, mu is
19
* precomputed via mp_reduce_setup.
20
* From HAC pp.604 Algorithm 14.42
22
int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
25
int res, um = m->used;
28
if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
32
/* q1 = x / b**(k-1) */
35
/* according to HAC this optimization is ok */
36
if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
37
if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
41
#ifdef BN_S_MP_MUL_HIGH_DIGS_C
42
if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
45
#elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
46
if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
57
/* q3 = q2 / b**(k+1) */
60
/* x = x mod b**(k+1), quick (no division) */
61
if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
65
/* q = q * m mod b**(k+1), quick (no division) */
66
if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
71
if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
75
/* If x < 0, add b**(k+1) to it */
76
if (mp_cmp_d (x, 0) == MP_LT) {
78
if ((res = mp_lshd (&q, um + 1)) != MP_OKAY)
80
if ((res = mp_add (x, &q, x)) != MP_OKAY)
84
/* Back off if it's too big */
85
while (mp_cmp (x, m) != MP_LT) {
86
if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
98
/* $Source: /cvs/libtom/libtommath/bn_mp_reduce.c,v $ */
99
/* $Revision: 1.4 $ */
100
/* $Date: 2006/12/28 01:25:13 $ */