1 /* Test for mpn_invert function.
3 Contributed to the GNU project by Marco Bodrato.
5 Copyright 2009 Free Software Foundation, Inc.
7 This file is part of the GNU MP Library.
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
14 The GNU MP Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17 License for more details.
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
30 /* Sizes are up to 2^SIZE_LOG limbs */
39 #define MAX_N (1L << SIZE_LOG)
44 invert_valid (mp_srcptr ip, mp_srcptr dp, mp_size_t n)
51 tp = TMP_ALLOC_LIMBS (2*n);
53 refmpn_mul (tp, ip, n, dp, n);
54 cy = refmpn_add_n (tp + n, tp + n, dp, n); /* This must not give a carry. */
55 cy -= refmpn_add (tp, tp, 2*n, dp, n); /* This must give a carry. */
62 Chech the result of the mpn_invert function in the library.
66 main (int argc, char **argv)
68 mp_ptr ip, dp, scratch;
71 gmp_randstate_ptr rands;
78 count = strtol (argv[1], &end, 0);
79 if (*end || count <= 0)
81 fprintf (stderr, "Invalid test count: %s.\n", argv[1]);
89 dp = TMP_ALLOC_LIMBS (MAX_N);
90 ip = 1+TMP_ALLOC_LIMBS (MAX_N + 2);
92 = 1+TMP_ALLOC_LIMBS (mpn_invert_itch (MAX_N) + 2);
94 for (test = 0; test < count; test++)
100 mp_limb_t i_before, i_after, s_before, s_after;
102 for (size_min = 1; (1L << size_min) < MIN_N; size_min++)
105 /* We generate an in the MIN_N <= n <= (1 << size_range). */
106 size_range = size_min
107 + gmp_urandomm_ui (rands, SIZE_LOG + 1 - size_min);
110 + gmp_urandomm_ui (rands, (1L << size_range) + 1 - MIN_N);
114 mpn_random2 (ip-1, n + 2);
118 itch = mpn_invert_itch (n);
119 ASSERT_ALWAYS (itch <= mpn_invert_itch (MAX_N));
120 mpn_random2 (scratch-1, itch+2);
121 s_before = scratch[-1];
122 s_after = scratch[itch];
124 dp[n-1] |= GMP_NUMB_HIGHBIT;
125 mpn_invert (ip, dp, n, scratch);
126 if (ip[-1] != i_before || ip[n] != i_after
127 || scratch[-1] != s_before || scratch[itch] != s_after
128 || ! invert_valid(ip, dp, n))
130 printf ("ERROR in test %d, n = %d\n",
132 if (ip[-1] != i_before)
134 printf ("before ip:"); mpn_dump (ip -1, 1);
135 printf ("keep: "); mpn_dump (&i_before, 1);
137 if (ip[n] != i_after)
139 printf ("after ip:"); mpn_dump (ip + n, 1);
140 printf ("keep: "); mpn_dump (&i_after, 1);
142 if (scratch[-1] != s_before)
144 printf ("before scratch:"); mpn_dump (scratch-1, 1);
145 printf ("keep: "); mpn_dump (&s_before, 1);
147 if (scratch[itch] != s_after)
149 printf ("after scratch:"); mpn_dump (scratch + itch, 1);
150 printf ("keep: "); mpn_dump (&s_after, 1);