Jacobi via reciprocity
int jacobi(long a, long n) {
a = ((a % n) + n) % n;
int result = 1;
while (a != 0) {
while ((a & 1) == 0) {
a /= 2;
if (n % 8 == 3 || n % 8 == 5) result = -result;
}
long t = a; a = n; n = t;
if (a % 4 == 3 && n % 4 == 3) result = -result;
a %= n;
}
return n == 1 ? result : 0;
}Advertisement
Solovay-Strassen primality
Test a^((n-1)/2) ≡ (a/n) mod n. Composite fails with prob ≥ 1/2.
Advertisement
Complexity
O(log² n) with fast integer arithmetic. Comparable to gcd.
Applications
Primality tests (Solovay-Strassen). Tonelli-Shanks non-residue selection. RSA sanity checks.