当前位置: 代码迷 >> 综合 >> HihoCoder--1287--Miller-Rabin质数测试
  详细解决方案

HihoCoder--1287--Miller-Rabin质数测试

热度:48   发布时间:2023-12-12 06:11:26.0

题目不再多叙述:Miller-Rabin质数测试;

思路:https://blog.csdn.net/queque_heiya/article/details/105928679

https://blog.csdn.net/queque_heiya/article/details/105929064

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
LL mul_mod(LL a,LL b,LL mod){LL ret=0;while(b){if(b&1)    ret=ret+a;if(ret>=mod)	ret-=mod;a=a+a;if(a>=mod)	a-=mod;b>>=1;}return ret;
}
LL pow_mod(LL a,LL b,LL mod){LL ret=1;while(b){if(b&1)ret=mul_mod(ret,a,mod);a=mul_mod(a,a,mod);b>>=1;}return ret;
}
bool Miller_Rabin(LL n){//判断素数 LL u=n-1,pre,x;int i,j,k=0;if(n==2||n==3||n==5||n==7||n==11)	return true;if(n==1||(!(n%2))||(!(n%3))||(!(n%5))||(!(n%7))||(!(n%11))) returnfalse;//初始化判断素数 for(;!(u&1);k++,u>>=1);//按照要求转换形式 for(i=0;i<5;i++){x=rand()%(n-2)+2;//生成随机数 x=pow_mod(x,u,n);pre=x;for(j=0;j<k;j++){x=mul_mod(x,x,n);if(x==1&&pre!=1&&pre!=(n-1))//二次探测判断 return false;pre=x;}if(x!=1) return false;//用费马小定理判断 }return true;
}
int main(){LL n,T;scanf("%lld",&T);while(T--){scanf("%lld",&n);if(Miller_Rabin(n)) puts("Yes");else puts("No");}return 0;
}

 

  相关解决方案