前置芝士

费马小定理:当 \(p\) 为质数且 \(a,p\) 互质时,\(a^{p-1}\equiv 1\pmod p\)

二次剩余定理:若 \(p\) 为质数且 \(x^2\equiv 1\pmod p\),则 \(x\equiv 1\pmod p\)\(x\equiv p-1\pmod p\)

实现方法

  • 枚举素数。若 \(x=p\),则 \(x\) 为素数;若 \(x\bmod p=0\),则 \(x\) 为合数。
  • 判断 \(p^{x-1}\equiv 1\pmod x\) 是否成立,不成立则为合数。
  • \(k\leftarrow x-1\),重复以下操作至 \(k\) 为偶数:
    • \(k\leftarrow \frac k2\)\(t\leftarrow p^k\bmod x\)
    • \(t\neq 1\land t\neq x-1\),返回 \(\texttt{false}\)
    • \(t=x-1\),返回 \(\texttt{true}\)

Code

const int cnt=10,pri[cnt]={2,3,5,7,11,13,19,61,2333,24251};
inline bool check(int x,int p){
	if(x%p==0||power(p%x,x-1,x)!=1)return false;
	int k=x-1;
	while(k){
		int t=power(p,k>>=1,x);
		if(t!=1&&t!=x-1)return false;
		if(k&1==1||t==x-1)return true;
	}
	return true;
}
inline bool IsPrime(int x){
	if(x<2)return false;
	for(int i=0;i<cnt;++i){
		if(x==pri[i])return true;
		if(!check(x,pri[i]))return false;
	}
	return true;
}