跳到正文

剪贴板

剪贴板 sw8ndzqz

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include<fstream>
#include<iostream>
#define auto unsigned long long
using namespace std;
const int tl=12;
const auto p[]={2,3,5,7,11,13,17,19,23,29,31,37};
/*auto product(auto x,auto y,auto mod)//防止溢出的乘法
{
	auto res=x*y-(auto)((long double)x/mod*y+0.5)*mod;
	return res;
}  */
auto product(auto x,auto y,auto mod)//另一种防止溢出的乘法
{
	return (__int128)x*y%mod;
}
auto power(auto x,auto a,auto mod)//快速幂
{
	if(a==0)return 1;
	auto res=power(x,a>>1,mod);
	res=product(res,res,mod);
	if((a&1)==1)res=product(res,x,mod);
	return res;
}
bool Miller_Rabin(auto x)
{
	if(x==1)return 0;//特判
	for(int i=0;i<tl;i++)
	{
		if(x==p[i])return 1;//显然
		bool ok=0;
		auto v=x-1;
		while((v&1)==0)v>>=1;
		auto y=power(p[i],v,x);
		if(y==1)ok=1;
		else
		{
			while(v<x-1)
			{
				if(y==x-1)
				{
					ok=1;
					break;
				}
				v<<=1;
				y=product(y,y,x);
			}
		}
		if(!ok)return 0;
	}
	return 1;
}
int main()
{
	auto a;
	cin>>a;
	cout<<Miller_Rabin(a);
	return 0;
}