1 #include "tommath_private.h"
2 #ifdef BN_MP_ROOT_U32_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* find the n'th root of an integer
8 * Result found such that (c)**b <= a and (c+1)**b > a
10 * This algorithm uses Newton's approximation
11 * x[i+1] = x[i] - f(x[i])/f'(x[i])
12 * which will find the root in log(N) time where
13 * each step involves a fair bit.
15 mp_err mp_root_u32(const mp_int *a, uint32_t b, mp_int *c)
17 mp_int t1, t2, t3, a_;
22 /* input must be positive if b is even */
23 if (((b & 1u) == 0u) && (a->sign == MP_NEG)) {
27 if ((err = mp_init_multi(&t1, &t2, &t3, NULL)) != MP_OKAY) {
31 /* if a is negative fudge the sign but keep track */
35 /* Compute seed: 2^(log_2(n)/b + 2)*/
36 ilog2 = mp_count_bits(a);
39 If "b" is larger than INT_MAX it is also larger than
40 log_2(n) because the bit-length of the "n" is measured
41 with an int and hence the root is always < 2 (two).
43 if (b > (uint32_t)(INT_MAX/2)) {
50 /* "b" is smaller than INT_MAX, we can cast safely */
57 ilog2 = ilog2 / ((int)b);
64 /* Start value must be larger than root */
66 if ((err = mp_2expt(&t2,ilog2)) != MP_OKAY) goto LBL_ERR;
69 if ((err = mp_copy(&t2, &t1)) != MP_OKAY) goto LBL_ERR;
71 /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */
74 if ((err = mp_expt_u32(&t1, b - 1u, &t3)) != MP_OKAY) goto LBL_ERR;
78 if ((err = mp_mul(&t3, &t1, &t2)) != MP_OKAY) goto LBL_ERR;
81 if ((err = mp_sub(&t2, &a_, &t2)) != MP_OKAY) goto LBL_ERR;
84 /* t3 = t1**(b-1) * b */
85 if ((err = mp_mul_d(&t3, b, &t3)) != MP_OKAY) goto LBL_ERR;
87 /* t3 = (t1**b - a)/(b * t1**(b-1)) */
88 if ((err = mp_div(&t2, &t3, &t3, NULL)) != MP_OKAY) goto LBL_ERR;
90 if ((err = mp_sub(&t1, &t3, &t2)) != MP_OKAY) goto LBL_ERR;
93 Number of rounds is at most log_2(root). If it is more it
94 got stuck, so break out of the loop and do the rest manually.
99 } while (mp_cmp(&t1, &t2) != MP_EQ);
101 /* result can be off by a few so check */
102 /* Loop beneath can overshoot by one if found root is smaller than actual root */
104 if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
105 cmp = mp_cmp(&t2, &a_);
111 if ((err = mp_add_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
116 /* correct overshoot from above or from recurrence */
118 if ((err = mp_expt_u32(&t1, b, &t2)) != MP_OKAY) goto LBL_ERR;
119 if (mp_cmp(&t2, &a_) == MP_GT) {
120 if ((err = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY) goto LBL_ERR;
129 /* set the sign of the result */
135 mp_clear_multi(&t1, &t2, &t3, NULL);