1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is library that provides for multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library is designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
17 /* find the n'th root of an integer
19 * Result found such that (c)**b <= a and (c+1)**b > a
21 * This algorithm uses Newton's approximation
22 * x[i+1] = x[i] - f(x[i])/f'(x[i])
23 * which will find the root in log(N) time where
24 * each step involves a fair bit. This is not meant to
25 * find huge roots [square and cube, etc].
28 mp_n_root (mp_int * a, mp_digit b, mp_int * c)
33 /* input must be positive if b is even */
34 if ((b & 1) == 0 && a->sign == MP_NEG) {
38 if ((res = mp_init (&t1)) != MP_OKAY) {
42 if ((res = mp_init (&t2)) != MP_OKAY) {
46 if ((res = mp_init (&t3)) != MP_OKAY) {
50 /* if a is negative fudge the sign but keep track */
59 if ((res = mp_copy (&t2, &t1)) != MP_OKAY) {
63 /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */
66 if ((res = mp_expt_d (&t1, b - 1, &t3)) != MP_OKAY) {
72 if ((res = mp_mul (&t3, &t1, &t2)) != MP_OKAY) {
77 if ((res = mp_sub (&t2, a, &t2)) != MP_OKAY) {
82 /* t3 = t1**(b-1) * b */
83 if ((res = mp_mul_d (&t3, b, &t3)) != MP_OKAY) {
87 /* t3 = (t1**b - a)/(b * t1**(b-1)) */
88 if ((res = mp_div (&t2, &t3, &t3, NULL)) != MP_OKAY) {
92 if ((res = mp_sub (&t1, &t3, &t2)) != MP_OKAY) {
95 } while (mp_cmp (&t1, &t2) != MP_EQ);
97 /* result can be off by a few so check */
99 if ((res = mp_expt_d (&t1, b, &t2)) != MP_OKAY) {
103 if (mp_cmp (&t2, a) == MP_GT) {
104 if ((res = mp_sub_d (&t1, 1, &t1)) != MP_OKAY) {
112 /* reset the sign of a first */
118 /* set the sign of the result */