luogu P5736 【【深基7.例2】质数筛】


看见题解区没有用Miller-Rabin,所以我来了

这道题不需要打素数表,只要直接判断输出即可。


算法介绍:Miller-Rabin

1
2
Miller-Rabin素性检验是一种素数判定法则,利用随机化算法判断一个数是合数还是可能是素数。
---百度百科

Miller-Rabin算法是一种随机化的算法,可以大概率的检测出一个数是合数还是质数,它依赖于费马小定理和二次探测两个理论,若测试次数为a,则该算法出错几率为\(4^{-a}\)不会证(逃。两个理论的相关证明(引用于CSDN)

1
2
费马小定理(Fermat's little theorem)是数论中的一个重要定理,在1636年提出。如果p是一个质数,而整数a不是p的倍数,则有a^(p-1)≡1(mod p)。
--百度百科
根据费马小定理,如果 p 为质数且 a 与 p 互质,那么有\(a^{p−1}≡1(mod\quad p)\),我们随机出一个a,用快速幂得到\(a^{p-1}mod\quad p\),若结果为1,则再次测试,若结果不为1,则p一定为合数,结束测试,通常,只需随机出10个值便可基本测出是否为质数。

Code:

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
#include <cstdio>
#include <cstdlib>
using namespace std;
int n;
int pow(int a,int b,int m)
{
if(b==1)
return a%m;
long long ans=1,p=a;
while(b)
{
if(b&1)
ans=ans*p%m;
p=p*p%m;
b>>=1;
}
return ans%m;
}
bool Mr(int s)
{
if(s==1)
return 0;
if(s==2)
return 1;
for(int i=1;i<=10;i++)
{
int a=rand()%(s-2)+2;
if(pow(a,s-1,s)!=1)
return 0;
}
return 1;
}
int main()
{
scanf("%d",&n);
while(n--)
{
int w;
scanf("%d",&w);
if(Mr(w))
printf("%d ",w);
}
return 0;
}