1702 素数判定 2[[一中数论随堂练]

1702 素数判定 2

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 钻石 Diamond
 
 
 
题目描述 Description

一个数,他是素数么?

设他为P满足(P<=263-1)

 

输入描述 Input Description

P

输出描述 Output Description

Yes|No

样例输入 Sample Input

2

 

样例输出 Sample Output

Yes

 

数据范围及提示 Data Size & Hint

算法导论——数论那一节
注意Carmichael Number

分类标签 Tags 点此展开 

 
 
题解:费马小定理判断麦森数是否是质数
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<algorithm>
#define ll long long
using namespace std;
ll mod;
ll mul(ll a,ll b){/*慢速乘法*/
    ll res=0;
    for(;a;a>>=1,b=(b+b)%mod) if(a&1) res=(res+b)%mod;
    return res;
}
ll fpow(ll a,ll p){/*快速幂 */
    ll res=1;
    for(;p;p>>=1,a=mul(a,a)%mod) if(p&1) res=mul(res,a)%mod;
    return res;
}
bool check(ll n){
    if(n==2) return 1;
    if((n<2)||!(n&1)) return 0;
    mod=n;
    for(ll i=0,x;i<10;i++){/*费马定理+验证法*/
        x=rand();
        if(x%n==0) continue;
        if(fpow(x,n-1)!=1) return 0;
    }
    return 1;
}
int main(){
    srand(time(0));
    ll x;scanf("%lld",&x);
    if(check(x)) puts("Yes");
    else puts("No");
    return 0;
}

 


 

posted @ 2016-07-10 19:31  神犇(shenben)  阅读(256)  评论(0)    收藏  举报