1 /*
2 Copyright (C) 2013 William Hart
3
4 This file is part of FLINT.
5
6 FLINT is free software: you can redistribute it and/or modify it under
7 the terms of the GNU Lesser General Public License (LGPL) as published
8 by the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version. See <http://www.gnu.org/licenses/>.
10 */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <gmp.h>
15 #include "flint.h"
16 #include "longlong.h"
17 #include "mpn_extras.h"
18 #include "ulong_extras.h"
19
main(void)20 int main(void)
21 {
22 int i, result;
23 mpz_t a, b, d, r1, r2;
24 gmp_randstate_t st;
25 mp_limb_t d1, d2, dinv;
26 mp_size_t size;
27 flint_bitcnt_t norm;
28
29 FLINT_TEST_INIT(state);
30
31 flint_printf("mulmod_preinv1....");
32 fflush(stdout);
33
34 mpz_init(a);
35 mpz_init(b);
36 mpz_init(d);
37 mpz_init(r1);
38 /* don't init r2 */
39
40 gmp_randinit_default(st);
41
42 for (i = 0; i < 10000; i++)
43 {
44 size = n_randint(state, 200) + 2;
45
46 mpz_rrandomb(a, st, size*FLINT_BITS);
47 mpz_rrandomb(b, st, size*FLINT_BITS);
48 do {
49 mpz_rrandomb(d, st, size*FLINT_BITS);
50 } while (mpz_sgn(d) == 0);
51
52 /* reduce a, b mod d */
53 mpz_fdiv_r(a, a, d);
54 mpz_fdiv_r(b, b, d);
55
56 mpz_mul(r1, a, b);
57 mpz_fdiv_r(r1, r1, d);
58
59 /* normalise */
60 count_leading_zeros(norm, d->_mp_d[d->_mp_size - 1]);
61 mpz_mul_2exp(a, a, norm);
62 mpz_mul_2exp(b, b, norm);
63 mpz_mul_2exp(d, d, norm);
64
65 d1 = d->_mp_d[size - 1];
66 d2 = d->_mp_d[size - 2];
67 dinv = flint_mpn_preinv1(d1, d2);
68
69 r2->_mp_d = flint_malloc(size*sizeof(mp_limb_t));
70
71 flint_mpn_mulmod_preinv1(r2->_mp_d, a->_mp_d, b->_mp_d, size, d->_mp_d, dinv, norm);
72
73 /* normalise */
74 while (size && r2->_mp_d[size - 1] == 0) size--;
75 r2->_mp_size = size;
76 r2->_mp_alloc = size;
77
78 result = (mpz_cmp(r1, r2) == 0);
79 if (!result)
80 {
81 flint_printf("FAIL:\n");
82 gmp_printf("%Zd\n", a);
83 gmp_printf("%Zd\n", b);
84 gmp_printf("%Zd\n", d);
85 gmp_printf("%Zd\n", r1);
86 gmp_printf("%Zd\n", r2);
87 abort();
88 }
89
90 flint_free(r2->_mp_d);
91 }
92
93 mpz_clear(a);
94 mpz_clear(b);
95 mpz_clear(d);
96 mpz_clear(r1);
97 /* don't init r2 */
98
99 gmp_randclear(st);
100 FLINT_TEST_CLEANUP(state);
101
102 flint_printf("PASS\n");
103 return 0;
104 }
105