Skip to content

Commit fe26e96

Browse files
committed
Miller-Rabin素数测试
1 parent cea146e commit fe26e96

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Miller-Rabin.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <cstdio>
2+
#include <cstdlib>
3+
4+
#define LOWBIT(x) ((x) & (-(x)))
5+
6+
#define COMPOSITE 0
7+
#define PRIME 1
8+
9+
typedef long long ll;
10+
11+
using namespace std;
12+
13+
ll qpow(ll x, int y, int p)
14+
{
15+
if (y == 0) return 1;
16+
ll h = qpow(x * x % p, y >> 1, p);
17+
if ((y & 1) == 0) return h;
18+
else return h * x % p;
19+
}
20+
21+
bool witness(int a, int n)
22+
{
23+
int t = LOWBIT(n - 1);
24+
int u = n / t;
25+
ll x = qpow(a, u, n);
26+
for (int i = 1; i < t; i <<= 1)
27+
{
28+
ll r = x * x % (ll)n;
29+
if (r == 1 && x != 1 && x != n - 1) return true;
30+
x = r;
31+
}
32+
if (x != 1) return true;
33+
return false;
34+
}
35+
36+
bool Miller_Rabin(int n, int s)
37+
{
38+
if (n == 2) return PRIME;
39+
if ((n & 1) == 0) return COMPOSITE;
40+
while (s--)
41+
{
42+
if (witness(rand() % (n - 2) + 2, n) == true) return COMPOSITE;
43+
}
44+
return PRIME;
45+
}
46+
47+
int main()
48+
{
49+
int n;
50+
while (true)
51+
{
52+
scanf("%d", &n);
53+
printf("%s\n", Miller_Rabin(n, 10) == COMPOSITE ? "COMPOSITE" : "PRIME");
54+
}
55+
return 0;
56+
}

0 commit comments

Comments
 (0)