zoukankan      html  css  js  c++  java
  • HDU 2138 How many prime numbers(Miller_Rabin法判断素数 【*模板】 用到了快速幂算法 )

    How many prime numbers

    Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 12955    Accepted Submission(s): 4490


    Problem Description
      Give you a lot of positive integers, just to find out how many prime numbers there are.
     
    Input
      There are a lot of cases. In each case, there is an integer N representing the number of integers to find. Each integer won’t exceed 32-bit signed integer, and each of them won’t be less than 2.
     
    Output
      For each case, print the number of prime numbers you have found out.
     
    Sample Input
    3
    2 3 4
     
    Sample Output
    2
     
    算法:每次输入一个数直接判断暴力sqrt判断该数字是不是素数,然后累加素数的个数,也可以水过。
    但是也可以拿这道水题那练习Miller_Rabin判断素数法!时间复杂度比较低!
    代码:
    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <algorithm>
    
    using namespace std;
    
    long long pow_mod(long long a, long long i, long long n)
    {
    	if(i==0) return 1%n;
    	long long temp=pow_mod(a, i>>1, n);
    	temp = temp*temp%n;
    	if(i&1)
    		temp = (long long)temp*a%n;
    	return temp;
    }
    
    
    bool test(int n, int a, int dd)
    {
    	if(n==2) return true;
    	if(n==a) return true;
    	if( (n&1)==0 ) return false;
    	while(!(dd&1)) dd=dd>>1;
    
    	int t=pow_mod(a, dd, n); //调用快速幂函数
    	while((dd!=n-1) &&(t!=1) && (t!=n-1) )
    	{
    		t = (long long)t*t%n;
    		dd=dd<<1;
    	}
        return (t==n-1 || (dd&1)==1 );
    }
    
    bool Miller_Rabin_isPrime(int n)  //O(logN)
    {
    	if(n<2) return false;
    	int a[]={2, 3, 61}; //
    	for(int i=0; i<3; i++)
    		if(!test(n, a[i], n-1) )
    			return false;
    	return true;
    }
    
    int main()
    {
        int n;
        while(scanf("%d", &n)!=EOF)
        {
            int dd;
            int cnt=0;
            while(n--)
            {
                scanf("%d", &dd);
                if(Miller_Rabin_isPrime(dd))
                    cnt++;
            }
            printf("%d
    ", cnt );
        }
        return 0;
    }
    
  • 相关阅读:
    机器学习之线性回归
    机器学*-K*邻算法模型预测实战
    机器学习-特征抽取
    机器学习sklearn和字典特征抽取
    机器学习第一讲
    spark统计每个省份广告点击量top3
    spark统计单位时间内访问量
    并发容器之 ConcurrentHashMap源码剖析
    并发之 Java中的锁
    并发之 深入剖析volatile底层原理
  • 原文地址:https://www.cnblogs.com/yspworld/p/4343044.html
Copyright © 2011-2022 走看看