首页 > 编程语言 > 详细

HDU 2138 How many prime numbers(Miller_Rabin法判断素数 【*模板】 用到了快速幂算法 )

时间:2015-03-16 23:03:47      阅读:507      评论:0      收藏:0      [点我收藏+]

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\n", cnt );
    }
    return 0;
}

 

HDU 2138 How many prime numbers(Miller_Rabin法判断素数 【*模板】 用到了快速幂算法 )

原文:http://www.cnblogs.com/yspworld/p/4343044.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!