-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjacobi.cpp
More file actions
44 lines (37 loc) · 828 Bytes
/
jacobi.cpp
File metadata and controls
44 lines (37 loc) · 828 Bytes
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
#include <iostream>
using namespace std;
/* Precondition: a, n >= 0; n is odd */
int jacobi(int a, int n) {
int ans;
if (a == 0)
ans = (n == 1) ? 1 : 0;
else if (a == 2) {
switch ( n % 8 ) {
case 1:
case 7:
ans = 1;
break;
case 3:
case 5:
ans = -1;
break;
}
}
else if ( a >= n )
ans = jacobi(a%n, n);
else if ( a % 2 == 0 )
ans = jacobi(2,n)*jacobi(a/2, n);
else
ans = ( a % 4 == 3 && n % 4 == 3 ) ? -jacobi(n,a) : jacobi(n,a);
return ans;
}
int main()
{
int a, n;
cout << "a? ";
cin >> a;
cout << "n? ";
cin >> n;
cout << "\nThe Jacobi symbol is " << jacobi(a,n) << endl;
return 0;
}