1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
Copyright (C) 2012 William Hart
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include "ulong_extras.h"
/* compute square roots of a modulo m given factorisation of m */
slong n_sqrtmodn(ulong ** sqrt, ulong a, n_factor_t * fac)
{
ulong m = 1, minv = 1;
slong i, j, num;
ulong * x, * sn, * ind, ** s;
/* Check if modulus is one, that is, it has a trivial representation */
if (fac->num == 0)
{
*sqrt = flint_malloc(sizeof(ulong));
(*sqrt)[0] = 0;
return 1;
}
x = flint_malloc(sizeof(ulong)*fac->num);
sn = flint_malloc(sizeof(ulong)*fac->num);
ind = flint_malloc(sizeof(ulong)*fac->num);
s = flint_malloc(sizeof(ulong *)*fac->num);
/* compute prime powers and square roots of a mod x_i = p_i^r_i*/
num = 1;
for (i = 0; i < fac->num; i++)
{
ind[i] = 0;
x[i] = n_pow(fac->p[i], fac->exp[i]);
sn[i] = n_sqrtmod_primepow(s + i, a % x[i], fac->p[i], fac->exp[i]);
num *= sn[i];
if (num == 0)
{
for (j = 0; j < i; j++)
flint_free(s[j]);
flint_free(ind);
flint_free(x);
flint_free(s);
flint_free(sn);
*sqrt = NULL;
return 0;
}
}
*sqrt = flint_malloc(num*sizeof(ulong));
/*
compute values s_i = 1 mod x_i and s_i = 0 mod x_j for j != i
then replace sqrts a_i with a_i * s_i mod m = x_1*x_2*...*x_n
*/
for (i = 0; i < fac->num; i++)
{
ulong xp = 1, si;
/* compute product of x_j for j != i */
for (j = 0; j < i; j++)
xp *= x[j];
for (j = i + 1; j < fac->num; j++)
xp *= x[j];
/* compute m and precomputed inverse */
if (i == 0)
{
m = xp*x[i];
minv = n_preinvert_limb(m);
}
/* compute s_i */
si = xp*n_invmod(xp % x[i], x[i]);
/* a_i*s_i mod m for each sqrt a_i of a mod x_i*/
for (j = 0; (ulong) j < sn[i]; j++)
s[i][j] = n_mulmod2_preinv(si, s[i][j], m, minv);
}
/*
compute all the square roots by computing
sum_{i=0}^{fac->num} s[i][j] for each different permutation
of j's, all modulo m
*/
for (i = 0; i < num; i++) /* loop through every possibility */
{
/* compute next root */
(*sqrt)[i] = 0;
for (j = 0; j < fac->num; j++)
(*sqrt)[i] = n_addmod((*sqrt)[i], s[j][ind[j]], m);
/* increment to next set of indices */
for (j = 0; j < fac->num; j++)
{
ind[j]++;
if (ind[j] != sn[j])
break;
ind[j] = 0;
}
}
/* clean up */
for (i = 0; i < fac->num; i++)
flint_free(s[i]);
flint_free(ind);
flint_free(x);
flint_free(s);
flint_free(sn);
return num;
}