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