• HDU2138 How many prime numbers


    本文版权归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
    ",ans);
    	}
    }
    
    int main()
    {
        work();
        return 0;
    }
    //有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
    

      

  • 相关阅读:
    [错误处理]UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
    [已解决]使用 apt-get update 命令提示 ...中被配置了多次
    linux各种版本查看方法
    [Pandas技巧] 如何把pandas dataframe对象或series对象转换成list
    linux下终止相关操作
    [错误处理]Vim卡死,无法输入是怎么回事?是不是按了Ctrl+S
    批量修改文件名称方法
    pycharm配置 自动运行指定脚本
    pip安装超时,更换国内镜像源安装
    命令行特殊字符名字转义
  • 原文地址:https://www.cnblogs.com/ljh2000-jump/p/6586216.html
Copyright © 2020-2023  润新知