Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d035b0c

Browse files
Merge pull request #106 from jineshparakh/master
Added Rabin Miller Algorithm
2 parents 35bb941 + 3e86866 commit d035b0c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎09- Number Theory/rabinMiller.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
#define ll long long
4+
#define ld long double
5+
#define rep(i,a,b) for(ll i=a;i<b;i++)
6+
#define repp(i,a,b) for(ll i=a;i<=b;i++)
7+
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
8+
#define endl "\n"
9+
10+
ll k = 6;
11+
ll exp(ll x, ll y, ll p) {
12+
ll res = 1;
13+
while (y) {
14+
if (y % 2)
15+
res = (res * x % p) % p;
16+
x = (x * x) % p;
17+
y /= 2;
18+
}
19+
return res;
20+
}
21+
22+
bool miller(ll d, ll n) {
23+
ll a = 2 + rand() % (n - 4);
24+
ll x = exp(a, d, n);
25+
if (x == 1 || x == n - 1)
26+
return true;
27+
while (d != n - 1) {
28+
x = (x * x) % n;
29+
d = d * 2;
30+
if (x == 1) return false;
31+
if (x == n - 1) return true;
32+
}
33+
return false;
34+
}
35+
bool isPrime(ll n) {
36+
if (n < 2 || n == 4) return false;
37+
if (n <= 3) return true;
38+
ll d = n - 1;
39+
while (!(d & 1)) {
40+
d /= 2;
41+
}
42+
rep(i, 0, k) {
43+
if (!miller(d, n))
44+
return false;
45+
}
46+
return true;
47+
}
48+
int main() {
49+
50+
ll n; cin >> n;
51+
cout << isPrime(n);
52+
return 0;
53+
54+
}
55+
56+
57+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /