libtommath/mp_sqrt.c

68 lines
1.4 KiB
C
Raw Normal View History

#include "tommath_private.h"
#ifdef MP_SQRT_C
2019-04-07 13:29:11 +00:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
2004-04-11 20:46:22 +00:00
/* this function is less generic than mp_n_root, simpler and faster */
mp_err mp_sqrt(const mp_int *arg, mp_int *ret)
2004-04-11 20:46:22 +00:00
{
2019-05-19 15:16:13 +00:00
mp_err err;
2017-08-30 18:23:46 +00:00
mp_int t1, t2;
2004-04-11 20:46:22 +00:00
2017-08-30 18:23:46 +00:00
/* must be positive */
if (mp_isneg(arg)) {
2017-08-30 18:23:46 +00:00
return MP_VAL;
}
2004-04-11 20:46:22 +00:00
2017-08-30 18:23:46 +00:00
/* easy out */
2019-10-24 15:43:31 +00:00
if (mp_iszero(arg)) {
2017-08-30 18:23:46 +00:00
mp_zero(ret);
return MP_OKAY;
}
2004-04-11 20:46:22 +00:00
2019-05-19 15:16:13 +00:00
if ((err = mp_init_copy(&t1, arg)) != MP_OKAY) {
return err;
2017-08-30 18:23:46 +00:00
}
2004-04-11 20:46:22 +00:00
2019-05-19 15:16:13 +00:00
if ((err = mp_init(&t2)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR2;
2017-08-30 18:23:46 +00:00
}
2004-04-11 20:46:22 +00:00
2017-08-30 18:23:46 +00:00
/* First approx. (not very bad for large arg) */
mp_rshd(&t1, t1.used/2);
2004-04-11 20:46:22 +00:00
2017-08-30 18:23:46 +00:00
/* t1 > 0 */
2019-05-19 15:16:13 +00:00
if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
2019-05-19 15:16:13 +00:00
if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
2019-05-19 15:16:13 +00:00
if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
/* And now t1 > sqrt(arg) */
do {
2019-05-19 15:16:13 +00:00
if ((err = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
2019-05-19 15:16:13 +00:00
if ((err = mp_add(&t1, &t2, &t1)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
2019-05-19 15:16:13 +00:00
if ((err = mp_div_2(&t1, &t1)) != MP_OKAY) {
2019-10-29 17:41:25 +00:00
goto LBL_ERR1;
2017-08-30 18:23:46 +00:00
}
/* t1 >= sqrt(arg) >= t2 at this point */
} while (mp_cmp_mag(&t1, &t2) == MP_GT);
2004-04-11 20:46:22 +00:00
2017-08-30 18:23:46 +00:00
mp_exch(&t1, ret);
2004-04-11 20:46:22 +00:00
2019-10-29 17:41:25 +00:00
LBL_ERR1:
2017-08-30 18:23:46 +00:00
mp_clear(&t2);
2019-10-29 17:41:25 +00:00
LBL_ERR2:
2017-08-30 18:23:46 +00:00
mp_clear(&t1);
2019-05-19 15:16:13 +00:00
return err;
2004-04-11 20:46:22 +00:00
}
2004-10-29 22:07:18 +00:00
#endif