MnZn 可爱 miller_rabin 求调
查看原帖
MnZn 可爱 miller_rabin 求调
704275
无名之雾楼主2024/5/17 22:41
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}
inline void write(int x){
    if(x==0){putchar('0');return;}
	int len=0,k1=x,c[10005];
	if(k1<0)k1=-k1,putchar('-');
	while(k1)c[len++]=k1%10+'0',k1/=10;
	while(len--)putchar(c[len]);
}
int fpow(int x,int y,int m){
	int res=1;
	x%=m;
	while(y){
		if(y&1)res=(res+x)%m;
		x=(x*x)%m;
		y>>=1;
	} 
	return res;
} 
bool witness(int a,int n){
	int u=n-1,t=0;
	while(u&1==0)u>>=1,t++;
	int x1=fpow(a,u,n);
	for(int i=1;i<=t;i++){
		int x2=fpow(x1,2,n);
		if(x2==1&&x1!=1&&x1!=n-1)return 1;
		x1=x2;
	}
	if(x1!=1)return 1;
	return 0;
}
bool miller_rabin(int n,int s){
	if(n<2)return 0;
	if(n==2)return 1;
	if(n%2==0)return 0;
	for(int i=0;i<s&&i<n;i++){
		srand(time(0)); 
		int a=rand()%(n-1)+1;
		if(witness(a,n))return 0;
	}
	return 1;
}
signed main(){
	int l=read(),r=read(),cnt=0;
	for(int i=l;i<=r;i++){
		if(miller_rabin(i,50))cnt++;
	}
	write(cnt);
	return 0;
}

样例死活过不去。

2024/5/17 22:41
加载中...