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
use integer::Integer;
use num_traits::{One, Signed, Zero};
use crate::BigInt;
pub fn jacobi(x: &BigInt, y: &BigInt) -> isize {
if !y.is_odd() {
panic!(
"invalid arguments, y must be an odd integer,but got {:?}",
y
);
}
let mut a = x.clone();
let mut b = y.clone();
let mut j = 1;
if b.is_negative() {
if a.is_negative() {
j = -1;
}
b = -b;
}
loop {
if b.is_one() {
return j;
}
if a.is_zero() {
return 0;
}
a = a.mod_floor(&b);
if a.is_zero() {
return 0;
}
let s = a.trailing_zeros().unwrap();
if s & 1 != 0 {
let bmod8 = b.get_limb(0) & 7;
if bmod8 == 3 || bmod8 == 5 {
j = -j;
}
}
let c = &a >> s;
if b.get_limb(0) & 3 == 3 && c.get_limb(0) & 3 == 3 {
j = -j
}
a = b;
b = c;
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_traits::FromPrimitive;
use crate::BigInt;
#[test]
fn test_jacobi() {
let cases = [
[0, 1, 1],
[0, -1, 1],
[1, 1, 1],
[1, -1, 1],
[0, 5, 0],
[1, 5, 1],
[2, 5, -1],
[-2, 5, -1],
[2, -5, -1],
[-2, -5, 1],
[3, 5, -1],
[5, 5, 0],
[-5, 5, 0],
[6, 5, 1],
[6, -5, 1],
[-6, 5, 1],
[-6, -5, -1],
];
for case in cases.iter() {
let x = BigInt::from_i64(case[0]).unwrap();
let y = BigInt::from_i64(case[1]).unwrap();
assert_eq!(case[2] as isize, jacobi(&x, &y), "jacobi({}, {})", x, y);
}
}
}