1 #include "tommath_private.h"
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* reduces x mod m, assumes 0 < x < m**2, mu is
7 * precomputed via mp_reduce_setup.
8 * From HAC pp.604 Algorithm 14.42
10 mp_err
mp_reduce(mp_int
*x
, const mp_int
*m
, const mp_int
*mu
)
17 if ((err
= mp_init_copy(&q
, x
)) != MP_OKAY
) {
21 /* q1 = x / b**(k-1) */
24 /* according to HAC this optimization is ok */
25 if ((mp_digit
)um
> ((mp_digit
)1 << (MP_DIGIT_BIT
- 1))) {
26 if ((err
= mp_mul(&q
, mu
, &q
)) != MP_OKAY
) {
29 } else if (MP_HAS(S_MP_MUL_HIGH
)) {
30 if ((err
= s_mp_mul_high(&q
, mu
, &q
, um
)) != MP_OKAY
) {
33 } else if (MP_HAS(S_MP_MUL_HIGH_COMBA
)) {
34 if ((err
= s_mp_mul_high_comba(&q
, mu
, &q
, um
)) != MP_OKAY
) {
42 /* q3 = q2 / b**(k+1) */
45 /* x = x mod b**(k+1), quick (no division) */
46 if ((err
= mp_mod_2d(x
, MP_DIGIT_BIT
* (um
+ 1), x
)) != MP_OKAY
) {
50 /* q = q * m mod b**(k+1), quick (no division) */
51 if ((err
= s_mp_mul(&q
, m
, &q
, um
+ 1)) != MP_OKAY
) {
56 if ((err
= mp_sub(x
, &q
, x
)) != MP_OKAY
) {
60 /* If x < 0, add b**(k+1) to it */
61 if (mp_cmp_d(x
, 0uL) == MP_LT
) {
63 if ((err
= mp_lshd(&q
, um
+ 1)) != MP_OKAY
) {
66 if ((err
= mp_add(x
, &q
, x
)) != MP_OKAY
) {
71 /* Back off if it's too big */
72 while (mp_cmp(x
, m
) != MP_LT
) {
73 if ((err
= s_mp_sub(x
, m
, x
)) != MP_OKAY
) {