隐藏
「poj3641」伪素数 - 快速幂 | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「poj3641」伪素数 - 快速幂

题目大意

    根据以$a$为基的伪素数的定义,判断$p$是否是以$a$为基的伪素数。($2\lt p\le1000000000,1\lt a\lt p$)


题目分析

这道题题意略不清。
在本题中的伪素数指$a^p\equiv a\pmod p$,且$p$不是素数。
然后写个快速幂和$O(\sqrt n)$判素数即可。
只有我这样的傻子才会写Miller-Rabin。


代码

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
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

typedef long long LL;

inline const LL Get_Int() {
LL num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

LL Quick_Pow(LL a,LL b,LL p) {
LL sum=1;
for(; b; b>>=1,a=a*a%p)if(b&1)sum=sum*a%p;
return sum;
}

const int TIMES=10;
mt19937 g(rand());

bool Witness(LL a,LL n) {
LL u=n-1,t=0;
while(u%2==0)t++,u>>=1;
LL x=Quick_Pow(a,u,n);
if(x==1)return false;
for(int i=1; i<=t; i++,x=x*x%n)
if(x!=n-1&&x!=1&&x*x%n==1)return true;
return x!=1;
}

bool Miller_Rabin(LL n) {
if(n==2)return true;
if(n<2||!(n&1))return false;
srand(time(NULL));
for(int i=1; i<=TIMES; i++)
if(Witness(g()%(n-1)+1,n))return false;
return true;
}

int main() {
while(true) {
LL p=Get_Int(),a=Get_Int();
if(p+a==0)break;
if(Miller_Rabin(p))puts("no");
else {
if(Quick_Pow(a,p,p)==a)puts("yes");
else puts("no");
}
}
return 0;
}
姥爷们赏瓶冰阔落吧~