Bump actions/upload-artifacts version
[libtommath.git] / mp_kronecker.c
blobe6bedc891248ae087cdd69634783fd5525f08dcf
1 #include "tommath_private.h"
2 #ifdef MP_KRONECKER_C
4 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
5 /* SPDX-License-Identifier: Unlicense */
7 /*
8 Kronecker symbol (a|p)
9 Straightforward implementation of algorithm 1.4.10 in
10 Henri Cohen: "A Course in Computational Algebraic Number Theory"
12 @book{cohen2013course,
13 title={A course in computational algebraic number theory},
14 author={Cohen, Henri},
15 volume={138},
16 year={2013},
17 publisher={Springer Science \& Business Media}
20 mp_err mp_kronecker(const mp_int *a, const mp_int *p, int *c)
22 mp_int a1, p1, r;
23 mp_err err;
24 int v, k;
26 static const char table[] = {0, 1, 0, -1, 0, -1, 0, 1};
28 if (mp_iszero(p)) {
29 if ((a->used == 1) && (a->dp[0] == 1u)) {
30 *c = 1;
31 } else {
32 *c = 0;
34 return MP_OKAY;
37 if (mp_iseven(a) && mp_iseven(p)) {
38 *c = 0;
39 return MP_OKAY;
42 if ((err = mp_init_copy(&a1, a)) != MP_OKAY) {
43 return err;
45 if ((err = mp_init_copy(&p1, p)) != MP_OKAY) {
46 goto LBL_KRON_0;
49 v = mp_cnt_lsb(&p1);
50 if ((err = mp_div_2d(&p1, v, &p1, NULL)) != MP_OKAY) {
51 goto LBL_KRON_1;
54 if ((v & 1) == 0) {
55 k = 1;
56 } else {
57 k = table[a->dp[0] & 7u];
60 if (mp_isneg(&p1)) {
61 p1.sign = MP_ZPOS;
62 if (mp_isneg(&a1)) {
63 k = -k;
67 if ((err = mp_init(&r)) != MP_OKAY) {
68 goto LBL_KRON_1;
71 for (;;) {
72 if (mp_iszero(&a1)) {
73 if (mp_cmp_d(&p1, 1uL) == MP_EQ) {
74 *c = k;
75 goto LBL_KRON;
76 } else {
77 *c = 0;
78 goto LBL_KRON;
82 v = mp_cnt_lsb(&a1);
83 if ((err = mp_div_2d(&a1, v, &a1, NULL)) != MP_OKAY) {
84 goto LBL_KRON;
87 if ((v & 1) == 1) {
88 k = k * table[p1.dp[0] & 7u];
91 if (mp_isneg(&a1)) {
93 * Compute k = (-1)^((a1)*(p1-1)/4) * k
94 * a1.dp[0] + 1 cannot overflow because the MSB
95 * of the type mp_digit is not set by definition
97 if (((a1.dp[0] + 1u) & p1.dp[0] & 2u) != 0u) {
98 k = -k;
100 } else {
101 /* compute k = (-1)^((a1-1)*(p1-1)/4) * k */
102 if ((a1.dp[0] & p1.dp[0] & 2u) != 0u) {
103 k = -k;
107 if ((err = mp_copy(&a1, &r)) != MP_OKAY) {
108 goto LBL_KRON;
110 r.sign = MP_ZPOS;
111 if ((err = mp_mod(&p1, &r, &a1)) != MP_OKAY) {
112 goto LBL_KRON;
114 if ((err = mp_copy(&r, &p1)) != MP_OKAY) {
115 goto LBL_KRON;
119 LBL_KRON:
120 mp_clear(&r);
121 LBL_KRON_1:
122 mp_clear(&p1);
123 LBL_KRON_0:
124 mp_clear(&a1);
126 return err;
129 #endif