[数论] [codevs 1702 素数判定2] 费马定理+验证法

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<string>
#include<assert.h>
using namespace std;
typedef unsigned long long LL;
LL p;
int prime[]={2,3,5,7,11,13,17,19,23,29};
/*慢速乘法*/ 
LL mul(LL a,LL b)
{
	LL ans = 0;
	for(LL i=a;i;i>>=1)
	{
		if(i&1)ans = (ans + b)%p;
		b = (b+b)%p;
	}
	return ans%p;
}
/*快速幂 */
LL mul1(LL a,LL b)
{
	LL ans = 1;
	for(LL i=a;i;i>>=1)
	{
		if(i&1)ans = mul(ans,b)%p;
		b = mul(b,b)%p;
	}
	return ans%p;
}
bool check()
{
	if(p==2)return true;
	else if(p<2||p&1==0)return false;
	/*费马定理+验证法*/ 
	for(int i=0;i<10;i++)
	{
		if(mul1(p-1,prime[i])!=1)return false;	
	}
	return true;
}

int main()
{
	cin>>p;
	if(check())cout<<"Yes";
	else cout<<"No";
	return 0;
}

你可能感兴趣的:(算法,数论)