时间:2016-05-10 12:48:09 星期二
题目编号:[2016-05-10][51nod][1106 质数检测]
题目大意:给出N个正整数,检测每个数是否为质数。如果是,输出”Yes”,否则输出”No”。
分析:
- 直接上模板
- 打sqrt(1E9)内的质数表,直接判断能否被所有质数整除即可
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef long long ll;
const int maxp = 31622 + 10;//sqrt(1E9)
int pri[maxp];
void inipri(){
memset(pri,0,sizeof(pri));
for(int i = 2 ; i < maxp ; ++i){
if(!pri[i]) pri[++pri[0]] = i;
for(int j = 1 ; j <= pri[0] && pri[j]*i < maxp;++j){
pri[pri[j] * i] = 1;
if(i % pri[j] == 0) break;
}
}
}
int main(){
inipri();
int n,a;
scanf("%d",&n);
for(int i = 0 ; i < n ; ++i){
scanf("%d",&a);
if((a & 1) == 0){
puts(a == 2 ? "Yes" : "No");
}else {
int flg = 1;
for(int j = 1; j < pri[0] && pri[j] * pri[j] < a;++j){
if(a % pri[j] == 0){
flg = 0;
break;
}
}
puts(flg ? "Yes" : "No");
}
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef long long ll;
ll muilt_mod(ll a, ll b ,ll c){
a %= c;
b %= c;
ll ret = 0;
ll tmp = a;
while(b){
if(b & 1){
ret += tmp;
if(ret > c) ret -= c;
}
tmp <<= 1;
if(tmp > c) tmp -= c;
b >>= 1;
}
return ret;
}
ll pow_mod(ll a, ll n, ll mod){
ll ret = 1;
ll tmp = a % mod;
while(n){
if(n & 1) ret = muilt_mod(ret,tmp,mod);
tmp = muilt_mod(tmp,tmp,mod);
n >>= 1;
}
return ret;
}
bool check(ll a, ll n , ll x,ll t){
ll ret = pow_mod(a,x,n);
ll last = ret;
for(int i = 1; i <= t; ++i){
ret = muilt_mod(ret,ret,n);
if(ret == 1 && last != 1 && last != n - 1) return true;
last = ret;
}
if(ret != 1) return true;
else return false;
}
bool Miller_Rabin(ll n){
if(n < 2) return false;
if(n == 2) return true;
if((n & 1) == 0 ) return false;
ll x = n - 1,t = 0;
while((x & 1) == 0){
x >>= 1;
++t;
}
srand(NULL);
int S = 8;
for(int i = 0 ; i < S;++i){
ll a = rand() % (n - 1) + 1;
if(check(a,n,x,t)) return false;
}
return true;
}
int main(){
int n,a;
scanf("%d",&n);
for(int i = 0 ; i < n ; ++i){
scanf("%d",&a);
puts(Miller_Rabin(a)?"Yes":"No");
}
return 0;
}