t-sqrt.c revision 1.1 1 1.1 mrg /*
2 1.1 mrg
3 1.1 mrg Copyright 2012, Free Software Foundation, Inc.
4 1.1 mrg
5 1.1 mrg This file is part of the GNU MP Library test suite.
6 1.1 mrg
7 1.1 mrg The GNU MP Library test suite is free software; you can redistribute it
8 1.1 mrg and/or modify it under the terms of the GNU General Public License as
9 1.1 mrg published by the Free Software Foundation; either version 3 of the License,
10 1.1 mrg or (at your option) any later version.
11 1.1 mrg
12 1.1 mrg The GNU MP Library test suite is distributed in the hope that it will be
13 1.1 mrg useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 1.1 mrg MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
15 1.1 mrg Public License for more details.
16 1.1 mrg
17 1.1 mrg You should have received a copy of the GNU General Public License along with
18 1.1 mrg the GNU MP Library test suite. If not, see http://www.gnu.org/licenses/. */
19 1.1 mrg
20 1.1 mrg #include <limits.h>
21 1.1 mrg #include <stdlib.h>
22 1.1 mrg #include <stdio.h>
23 1.1 mrg
24 1.1 mrg #include "testutils.h"
25 1.1 mrg
26 1.1 mrg #define MAXBITS 400
27 1.1 mrg #define COUNT 10000
28 1.1 mrg
29 1.1 mrg static void
30 1.1 mrg dump (const char *label, const mpz_t x)
31 1.1 mrg {
32 1.1 mrg char *buf = mpz_get_str (NULL, 16, x);
33 1.1 mrg fprintf (stderr, "%s: %s\n", label, buf);
34 1.1 mrg testfree (buf);
35 1.1 mrg }
36 1.1 mrg
37 1.1 mrg /* Called when s is supposed to be floor(sqrt(u)), and r = u - s^2 */
38 1.1 mrg static int
39 1.1 mrg sqrtrem_valid_p (const mpz_t u, const mpz_t s, const mpz_t r)
40 1.1 mrg {
41 1.1 mrg mpz_t t;
42 1.1 mrg
43 1.1 mrg mpz_init (t);
44 1.1 mrg mpz_mul (t, s, s);
45 1.1 mrg mpz_sub (t, u, t);
46 1.1 mrg if (mpz_sgn (t) < 0 || mpz_cmp (t, r) != 0)
47 1.1 mrg {
48 1.1 mrg mpz_clear (t);
49 1.1 mrg return 0;
50 1.1 mrg }
51 1.1 mrg mpz_add_ui (t, s, 1);
52 1.1 mrg mpz_mul (t, t, t);
53 1.1 mrg if (mpz_cmp (t, u) <= 0)
54 1.1 mrg {
55 1.1 mrg mpz_clear (t);
56 1.1 mrg return 0;
57 1.1 mrg }
58 1.1 mrg
59 1.1 mrg mpz_clear (t);
60 1.1 mrg return 1;
61 1.1 mrg }
62 1.1 mrg
63 1.1 mrg void
64 1.1 mrg testmain (int argc, char **argv)
65 1.1 mrg {
66 1.1 mrg unsigned i;
67 1.1 mrg mpz_t u, s, r;
68 1.1 mrg
69 1.1 mrg mpz_init (u);
70 1.1 mrg mpz_init (s);
71 1.1 mrg mpz_init (r);
72 1.1 mrg
73 1.1 mrg for (i = 0; i < COUNT; i++)
74 1.1 mrg {
75 1.1 mrg mini_rrandomb (u, MAXBITS);
76 1.1 mrg mpz_sqrtrem (s, r, u);
77 1.1 mrg
78 1.1 mrg if (!sqrtrem_valid_p (u, s, r))
79 1.1 mrg {
80 1.1 mrg fprintf (stderr, "mpz_sqrtrem failed:\n");
81 1.1 mrg dump ("u", u);
82 1.1 mrg dump ("sqrt", s);
83 1.1 mrg dump ("rem", r);
84 1.1 mrg abort ();
85 1.1 mrg }
86 1.1 mrg }
87 1.1 mrg mpz_clear (u);
88 1.1 mrg mpz_clear (s);
89 1.1 mrg mpz_clear (r);
90 1.1 mrg }
91