-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfermats_primality_test.cpp
99 lines (67 loc) · 1.25 KB
/
fermats_primality_test.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
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
Given the number, you are to answer the question: "Is it prime?"
Input
t – the number of test cases, then t test cases follows. [t <= 500]
Each line contains one integer: N [2 <= N <= 2^63-1]
Output
For each test case output string "YES" if given number is prime and "NO" otherwise.
Example
Input:
5
2
3
4
5
6
Output:
YES
YES
NO
YES
NO
#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
lli mulMod(lli a, lli b, lli c) {
lli x = 0, y = a % c;
while (b > 0) {
if (b % 2) {
x = (x + y) % c;
}
b /= 2;
y = (y * 2LL) % c;
}
return x % c;
}
lli binPower(lli x, lli y, lli mod) {
lli res = 1;
while (y) {
if (y % 2) res = mulMod(res, x, mod);
y /= 2;
x = mulMod(x, x, mod);
}
return res % mod;
}
bool isPrime(lli n, int iterations = 5) {
if (n <= 4) {
return n == 2 || n == 3;
}
for (int i = 1; i <= iterations; i++) {
lli a = 2 + rand() % (n - 3); // as 2 <= a <= (n - 2)
lli res = binPower(a, n - 1, n); // a^(n - 1) % n
if (res != 1) return false;
}
return true;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
cin >> t;
while (t--) {
lli n;
cin >> n;
if (isPrime(n)) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}