码迷,mamicode.com
首页 > 编程语言 > 详细

HDU 2138 How many prime numbers (判素数,米勒拉宾算法)

时间:2016-06-03 18:53:49      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

题意:给定一个数,判断是不是素数。

析:由于数太多,并且太大了,所以以前的方法都不适合,要用米勒拉宾算法。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
#include <cctype>

using namespace std;
typedef long long LL;
const int maxn = 1000 + 5;

LL qpow(int a, int b, int r){
    LL ans = 1;
    LL k = a % r;
    while(b){
        if(b & 1)  ans = (ans * k) % r;
        k = (k * k) % r;
        b >>= 1;
    }
    return ans;
}

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 = qpow(a, s, n);
    if(1 == k)  return true;
    for(int j = 0; j < r; ++j, k = k * k % n)
        if(k == n-1)  return true;
    return false;
}

bool is_prime(int n){
    int tab[] = {2, 3, 5, 7};
    for(int i = 0; i < 4; ++i){
        if(n == tab[i])  return true;
        if(!miller_rabbin(n, tab[i])) return false;
    }
    return true;
}

int main(){
//    freopen("in.txt", "r", stdin);
    int n, x;
    while(~scanf("%d", &n)){
        int cnt = 0;
        for(int i = 0; i < n; ++i){
            scanf("%d", &x);
            if(is_prime(x))  ++cnt;
        }
        printf("%d\n", cnt);
    }
}

 

HDU 2138 How many prime numbers (判素数,米勒拉宾算法)

标签:

原文地址:http://www.cnblogs.com/dwtfukgv/p/5557082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!