1
/* LibTomMath, multiple-precision integer library -- Tom St Denis
3
* LibTomMath is a library that provides multiple-precision
4
* integer arithmetic as well as number theoretic functionality.
6
* The library was 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
/* this function is less generic than mp_n_root, simpler and faster */
18
int mp_sqrt(mp_int *arg, mp_int *ret)
23
/* must be positive */
24
if (arg->sign == MP_NEG) {
29
if (mp_iszero(arg) == MP_YES) {
34
if ((res = mp_init_copy(&t1, arg)) != MP_OKAY) {
38
if ((res = mp_init(&t2)) != MP_OKAY) {
42
/* First approx. (not very bad for large arg) */
43
mp_rshd (&t1,t1.used/2);
46
if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) {
49
if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) {
52
if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) {
55
/* And now t1 > sqrt(arg) */
57
if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) {
60
if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) {
63
if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) {
66
/* t1 >= sqrt(arg) >= t2 at this point */
67
} while (mp_cmp_mag(&t1,&t2) == MP_GT);