1 /* $NetBSD: bn_mp_sqrt.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
7 * LibTomMath is a library that provides multiple-precision
8 * integer arithmetic as well as number theoretic functionality.
10 * The library was designed directly after the MPI library by
11 * Michael Fromberger but has been written from scratch with
12 * additional optimizations in place.
14 * The library is free for all purposes without any express
17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
20 /* this function is less generic than mp_n_root, simpler and faster */
21 int mp_sqrt(mp_int
*arg
, mp_int
*ret
)
26 /* must be positive */
27 if (arg
->sign
== MP_NEG
) {
32 if (mp_iszero(arg
) == MP_YES
) {
37 if ((res
= mp_init_copy(&t1
, arg
)) != MP_OKAY
) {
41 if ((res
= mp_init(&t2
)) != MP_OKAY
) {
45 /* First approx. (not very bad for large arg) */
46 mp_rshd (&t1
,t1
.used
/2);
49 if ((res
= mp_div(arg
,&t1
,&t2
,NULL
)) != MP_OKAY
) {
52 if ((res
= mp_add(&t1
,&t2
,&t1
)) != MP_OKAY
) {
55 if ((res
= mp_div_2(&t1
,&t1
)) != MP_OKAY
) {
58 /* And now t1 > sqrt(arg) */
60 if ((res
= mp_div(arg
,&t1
,&t2
,NULL
)) != MP_OKAY
) {
63 if ((res
= mp_add(&t1
,&t2
,&t1
)) != MP_OKAY
) {
66 if ((res
= mp_div_2(&t1
,&t1
)) != MP_OKAY
) {
69 /* t1 >= sqrt(arg) >= t2 at this point */
70 } while (mp_cmp_mag(&t1
,&t2
) == MP_GT
);
81 /* Source: /cvs/libtom/libtommath/bn_mp_sqrt.c,v */
83 /* Date: 2006/12/28 01:25:13 */