Remove building with NOCRYPTO option
[minix.git] / crypto / external / bsd / heimdal / dist / lib / hcrypto / libtommath / bn_mp_sqrt.c
blob8fc3d4b45d22eba543748fd999387ade5bd0a8d2
1 /* $NetBSD: bn_mp_sqrt.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
3 #include <tommath.h>
4 #ifdef BN_MP_SQRT_C
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
15 * guarantee it works.
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)
23 int res;
24 mp_int t1,t2;
26 /* must be positive */
27 if (arg->sign == MP_NEG) {
28 return MP_VAL;
31 /* easy out */
32 if (mp_iszero(arg) == MP_YES) {
33 mp_zero(ret);
34 return MP_OKAY;
37 if ((res = mp_init_copy(&t1, arg)) != MP_OKAY) {
38 return res;
41 if ((res = mp_init(&t2)) != MP_OKAY) {
42 goto E2;
45 /* First approx. (not very bad for large arg) */
46 mp_rshd (&t1,t1.used/2);
48 /* t1 > 0 */
49 if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) {
50 goto E1;
52 if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) {
53 goto E1;
55 if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) {
56 goto E1;
58 /* And now t1 > sqrt(arg) */
59 do {
60 if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) {
61 goto E1;
63 if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) {
64 goto E1;
66 if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) {
67 goto E1;
69 /* t1 >= sqrt(arg) >= t2 at this point */
70 } while (mp_cmp_mag(&t1,&t2) == MP_GT);
72 mp_exch(&t1,ret);
74 E1: mp_clear(&t2);
75 E2: mp_clear(&t1);
76 return res;
79 #endif
81 /* Source: /cvs/libtom/libtommath/bn_mp_sqrt.c,v */
82 /* Revision: 1.4 */
83 /* Date: 2006/12/28 01:25:13 */