summaryrefslogtreecommitdiff
path: root/math/millerRabin.cpp
blob: d41f33aba6ea7e9122d6ebfe6af98a29ad675331 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Theoretisch: n < 318,665,857,834,031,151,167,461 (> 10^23)
// Praktisch: n <= 10^18 (long long)
// Laufzeit: O(log n)
bool isPrime(ll n) {
	if(n == 2) return true;
	if(n < 2 || n % 2 == 0) return false;
	ll d=n-1,j=0;
	while(d % 2 == 0) d >>= 1, j++;
	for(int a = 2; a <= min((ll)37, n-1); a++) {
		ll v = pow_mod(a, d, n);
		if(v == 1 || v == n-1) continue;
		for(int i = 1;  i <= j; i++) {
			v = mult_mod(v, v, n);
			if(v == n-1 || v <= 1) break;
		}
		if(v != n-1) return false;
	}
	return true;
}