素数判定(米勒测试定理-费马小定理+快速乘)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<algorithm>
 6 #include<vector>
 7 #include<ctime>
 8 #define llg long long
 9 llg i,j,k,x,n,m;
10 using namespace std;
11 llg ksc(llg x,llg y,llg mo)  
12 {  
13     llg  t;  
14     x%=mo;  
15     for(t=0;y;x=(x<<1)%mo,y>>=1)  
16         if (y&1)  
17             t=(t+x)%mo;  
18     return t;  
19 }  
20 llg ksm(llg a,llg b,llg md)
21 {
22     llg ans=1;
23     a=a%md;
24     while (b!=0)
25     {
26         if (b % 2==1) ans=ksc(ans,a,md);
27         b/=2;
28         a=ksc(a,a,md);
29     }
30     return ans;
31 }
32 int main()
33 {
34     cin>>n;
35     if (n==2) {cout<<"Yes"; return 0;}
36     srand(time(NULL));
37     for (k=1;k<=10000;k++)
38     {
39         llg a=rand()%n;
40         if (ksm(a,n-1,n)!=1) {cout<<"No"; return 0;}
41     }
42     cout<<"Yes";
43     return 0;
44 }

 假设我们要判断n是否为素数:
  费马小定理告诉我们,若n满足:a^(n-1) % n==1 则n有很大概率为素数(反例是伪素数)若是n不满足这个式子则n一定为合数。那么我们随机几次a的值,再加以验证,这样就可以得到极为正确(但不一定正确)的结果。

  快速乘:即运用快速幂的思想来进行乘法,以防大整数相乘取模中的溢出。

posted @ 2016-05-31 21:27  №〓→龙光←  阅读(618)  评论(0编辑  收藏  举报