-
Notifications
You must be signed in to change notification settings - Fork 153
/
primality_check_fermat.cpp
61 lines (53 loc) · 1.25 KB
/
primality_check_fermat.cpp
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
/**
* Description: Fermats Primality Testing
* Usage: fermat
* Note: increating the no of iterations in fermat function improves accuracy (See Carmichael numbers). Usually I keep it 50.
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
long long mul(long long a,long long b,long long MOD){
long long a_high = a/1000000000;
long long a_low = a%1000000000;
long long b_high = b/1000000000;
long long b_low = b%1000000000;
long long result = (a_high*b_high)%MOD;
for(int i=0;i<9;i++){
result=(result*10)%MOD;
}
result=(result+a_high*b_low+a_low*b_high)%MOD;
for(int i=0;i<9;i++){
result=(result*10)%MOD;
}
result=(result+a_low*b_low)%MOD;
return result;
}
long long p(long long a,long long b,long long MOD){
if(b==0) return 1;
long long x=p(a,b/2,MOD);
if((b&1)==0) {
return mul(x,x,MOD);
} else {
return mul(mul(x,x,MOD),a,MOD);
}
}
bool fermat(long long num,int iterations){
if(num==1) {
return false;
} else if(num==2) {
return true;
} else {
for(int i=0;i<iterations;i++){
long long a=(rand()%(num-2))+2;
if(p(a,num-1,num)!=1) return false;
}
}
return true;
}
int main() {
int x;
cin >> x;
cout << fermat(x, 50) << endl;
}