本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。
本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!
题目链接:HDU2138
正解:$Miller-Rabin$素数测试+二次探测
解题报告:
$Millr-Rabin$素数测试:如果是直接按照费马小定理的逆定理的话,会被伪素数卡掉。
考虑引入二次探测的思想:原来的做法是先随一个$<=p-1$的数$check$一下$a^{p-1}$在模$p$意义下是不是$1$,如果是$1$那么认为$p$是质数。
我们把$p-1$分解成$2^c*q$的形式,然后我们先算$a^q$,算出来之后接下来就需要不断地平方了。
平方的过程中,我们如果发现某次的答案是$1$了也就是说上次的结果$x$,$x^2$在模$p$意义下是$1$,那么如果$p$是质数的话,$x=1$或$p-1$,否则$p$显然不是质数,每次$check$一下。
可以发现引入二次探测之后这个算法的正确性就会提高很多了。
(其实也就是把指数拆分之后多进行了一些$check$...)
//It is made by ljh2000
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <complex>
#include <bitset>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef complex<double> C;
const double pi = acos(-1);
LL n,ans;
inline LL getint(){
LL w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}
inline LL fast_pow(LL x,LL y,int p){
LL r=1;
while(y>0) {
if(y&1) r*=x,r%=p;
x*=x; x%=p;
y>>=1;
}
return r;
}
inline int MillerRabin(LL p){
if(p==1) return 0; if(p==2) return 1; if(p%2==0) return 0;
LL a,b=p-1,c,k=0; while(!(b&1)) b>>=1,k++; int T=5;
while(T--) {
a=rand()%(p-1)+1; a=fast_pow(a,b,p);
for(int i=1;i<=k;i++) {
c=fast_pow(a,2,p);//!!!
if(c==1 && a!=1 && a!=p-1) return 0;
a=c;
}
if(a!=1) return 0;
}
return 1;
}
inline void work(){
srand(time(NULL));
while(scanf("%lld",&n)!=EOF) {
ans=0;
for(int i=1;i<=n;i++) ans+=MillerRabin(getint());
printf("%lld\n",ans);
}
}
int main()
{
work();
return 0;
}
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。