您的位置:首页 > 编程语言 > C语言/C++

SGU113 水题 Easy Problem

2014-01-28 17:15 281 查看
问题:判断一个数是否是两个质数的乘积。

Problem: Nearly prime number is an integer positive number for which it is possible to find such primes P1 and P2 that given number is equal to P1*P2. There is given a sequence on N integer positive numbers, you are to write a program that prints “Yes” if
given number is nearly prime and “No” otherwise.

解法:筛法求质数,再枚举。枚举时要用O(Sqrt(N))的复杂度判断另一个质数。

Solution: Obtain prime numbers by sieving method, then enumerate them. Please note that you need to use the method of complexity of O(Sqrt(N)) to judge the other number whether it is a prime number in case it is very large.

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <math.h>
using namespace std;
int n,m,pnum,p[100100];
bool f[1000100];
bool isprime(int x) {
if (x<2) return 0;
for (int i=2;i*i<=x;i++)
if (x%i==0) return 0;
return 1;
}
int main() {
pnum = 0;
memset(f,0,sizeof(f));
f[1] = true;
for (int i=2;i<=1000010;i++)
if (!f[i]) {
pnum++;
p[pnum] = i;
for (int j=i+i;j<=1000010;j+=i) f[j] = true;
}

scanf("%d",&n);
while (n--) {
bool ans = false;
scanf("%d",&m);
for (int i=1;i<=pnum;i++) {
if (p[i]*p[i]>m) break;
if ((m%p[i]==0) && isprime(m/p[i])) {
ans = true;
break;
}
}
if (ans) printf("Yes\n");
else printf("No\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sgu C++ 质数