您的位置:首页 > 其它

hdu 2138 How many prime numbers(数论:素数判定)

2014-07-28 17:35 176 查看
因为给出的数据是32位,所以可以直接对每个数暴力判定

当然也可以用大素数判定Miller Rabin算法

两份代码如下:

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define LL long long
using namespace std;

bool judge(int n) {
int i;
int m = (int)sqrt(n+0.5);
for(i=2; i<=m; ++i)
if(n % i == 0)
return false;
return true;
}

int main(void) {
int n, i, cnt, x;
while(scanf("%d", &n) != EOF) {
cnt = 0;
for(i=0; i<n; ++i) {
scanf("%d", &x);
if(judge(x))
cnt++;
}
cout << cnt << endl;
}
return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<cmath>
bool witness(__int64 a,__int64 n) {
__int64 t, d, x;
d = 1;
int i=ceil(log(n-1.0)/log(2.0)) - 1;
for(; i>=0; i--) {
x = d;  d = (d*d)%n;
if(d==1 && x!=1 && x!=n-1) return true;
if( ((n-1) & (1<<i)) > 0)
d = (d*a)%n;
}
return d==1? false : true;
}
bool miller_rabin(__int64 n) {
if(n==2)    return true;
if(n==1 || ((n&1)==0))    return false;
for(int i=0;i<50;i++){
__int64 a=rand()*(n-2)/RAND_MAX +1;
if(witness(a, n))    return false;
}
return true;
}
int main() {
int n,cnt;
__int64 a;
while(scanf("%d",&n)!=EOF) {
cnt=0;
while(n--) {
scanf("%I64d",&a);
if(miller_rabin(a))
cnt++;
}
printf("%d\n",cnt);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: