HDU2138 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): 28963 Accepted Submission(s): 9629

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

Author
wangye

Source
HDU 2007-11 Programming Contest_WarmUp

問題鏈接HDU2138 How many prime numbers
問題簡述:統計素數的數量。
問題分析
    簡單模板題,不解釋。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的C++語言程序如下:

/* HDU2138 How many prime numbers */

#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ULL;

const int TIME = 5;

// 快速模冪計算
ULL powmod(ULL a, ULL n, ULL m)
{
    ULL res = 1LL;
    while(n) {
        if(n & 1LL) {        // n % 2 == 1
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        n >>= 1;
    }
    return res;
}

ULL random(ULL n)
{
    return (ULL)((double) rand() / RAND_MAX * n + 0.5);
}

bool check(ULL a, ULL n)
{
    ULL m = n - 1;
    int j = 0;
    while((m & 1) == 0) {j++; m >>= 1;}
    ULL x = powmod(a, m, n);
    if(x == 1 || x == n - 1)
        return false;
    while(j--) {
        x = x * x % n;
        if(x == n - 1)
            return false;
    }
    return true;
}

bool Miller_Rabin(ULL n)
{
    if(n < 2) return false;
    if(n == 2) return true;
    if((n & 1) == 0) return false;
    ULL x = n - 1;
    ULL t = 0;
    while((x&1) == 0) {
        x >>= 1;
        t++;
    }
    for(int i = 0; i <= TIME; i++)
    {
        ULL a = random(n - 2) + 1;
        if(check(a, n)) return false;
    }
    return true;
}

int main()
{
    int n;
    ULL m;
    while(~scanf("%d", &n)) {
        int ans = 0;
        while(n--) {
            scanf("%llu", &m);
            if(Miller_Rabin(m)) ans++;
        }

        printf("%d\n", ans);
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章