-
Notifications
You must be signed in to change notification settings - Fork 0
/
miller_rabin.cpp
167 lines (126 loc) · 2.66 KB
/
miller_rabin.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// BOJ 5615 아파트 임대
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
ll ipow(ll base, ll exp, ll mod) {
ll ret = 1;
base %= mod;
while (exp) {
if (exp & 1)
ret = (__int128)ret * base % mod;
exp >>= 1;
base = (__int128)base * base % mod;
}
return ret;
}
bool miller_rabin(ll x) {
if (x == 1)
return false;
int s = 0;
ll d = x - 1;
while (!(d & 1)) {
s++;
d >>= 1;
}
for (ll a : {2, 7, 61}) {
if (a >= x - 1)
break;
ll b = ipow(a, d, x);
if (b == 1 || b == x - 1)
continue;
if (s == 1)
return false;
bool flag = true;
for (int i = 0; i < s - 1; i++) {
b = (__int128)b * b % x;
if (b == x - 1) {
flag = false;
break;
}
}
if (flag)
return false;
}
return true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int q;
cin >> q;
int ans = 0;
while (q--) {
ll x;
cin >> x;
ans += miller_rabin(2 * x + 1);
}
cout << ans;
}
//--------------------------------------------------------------------------------
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
ll ipow(ll base, ll exp, ll mod) {
ll ret = 1;
base %= mod;
while (exp) {
if (exp & 1)
ret = (__int128)ret * base % mod;
exp >>= 1;
base = (__int128)base * base % mod;
}
return ret;
}
bool miller_rabin(ll x) {
if (x == 1)
return false;
int s = 0;
ll d = x - 1;
while (!(d & 1)) {
s++;
d >>= 1;
}
for (ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23}) {
if (a >= x - 1)
break;
ll b = ipow(a, d, x);
if (b == 1 || b == x - 1)
continue;
if (s == 1)
return false;
bool flag = true;
for (int i = 0; i < s - 1; i++) {
b = (__int128)b * b % x;
if (b == x - 1) {
flag = false;
break;
}
}
if (flag)
return false;
}
return true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int q;
cin >> q;
while (q--) {
ll x;
cin >> x;
cout << (miller_rabin(x) ? "Yes" : "No") << '\n';
}
}