HDU 2138 Miller-Rabin 模板题

求素数个数。

 

/** @Date    : 2017-09-18 23:05:15
  * @FileName: HDU 2138  miller-rabin 模板.cpp
  * @Platform: Windows
  * @Author  : Lweleth (SoungEarlf@gmail.com)
  * @Link    : https://github.com/
  * @Version : $Id$
  */
#include <bits/stdc++.h>
#define LL long long
#define PII pair<int ,int>
#define MP(x, y) make_pair((x),(y))
#define fi first
#define se second
#define PB(x) push_back((x))
#define MMG(x) memset((x), -1,sizeof(x))
#define MMF(x) memset((x),0,sizeof(x))
#define MMI(x) memset((x), INF, sizeof(x))
using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1e5+20;
const double eps = 1e-8;

LL fpow(LL a, LL n, LL mod)//快速幂 
{
    LL res = 1;
    while(n)
    {
        if(n & 1) res = (res * a) % mod;
        a = (a * a % mod + mod) % mod;
        n >>= 1;
    }
    return res;
}
bool Miller_Rabbin(int n,int a)//米勒拉宾素数测试 
{
    int r = 0, s = n - 1;
    if(!(n % a))
        return false;
    while(!(s & 1))
    {
        s>>=1;
        r++;
    }
    LL k = fpow(a, s, n);
    if(k == 1)
        return true;
    for(int j = 0; j < r; j++, k = k * k % n)
        if(k == n-1)
            return true;
    return false;
}
bool IsPrime(int n)//判断是否是素数 
{
    int tab[14] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41};
    for(int i = 0; i < 13; i++)
    {
        if(n == tab[i])
            return true;
        if(!Miller_Rabbin(n, tab[i]))
            return false;
    }
    return true;
}

int main()
{
	int n;
	while(cin >> n)
	{
		LL x;
		LL cnt = 0;
		for(int i = 0; i < n; i++)
			scanf("%ld", &x), cnt += (IsPrime(x)?1:0);
		printf("%lld\n", cnt);
	}
    return 0;
}
posted @ 2017-09-19 20:52  Lweleth  阅读(476)  评论(0编辑  收藏  举报