题目:
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer tТ-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains nspace-separated integers xi (1 ≤ xi ≤ 1012).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64dspecifier.
Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't.
3 4 5 6
YES NO NO
The given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".
思路:
如果一个数n只有三个约数,那么它的约数一定分别是,1,n,sqrt(n)。当sqrt(n)是素数时n不会有2到n-1的其他约数。
代码:
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define maxn 1000009
bool prime[maxn];//0表示素数,1表示不是素数
void init(){//筛选法效率更高
memset(prime,0,sizeof(prime));
prime[0]=prime[1]=1;
for(int i=2;i<=sqrt(maxn)+1;++i){
if(prime[i]) continue;
for(int j=i+i;j<=maxn;j+=i) prime[j]=1;
}
}
int main(){
__int64 t;
int flag,n;
init();
scanf("%d",&n);
while(n--){
scanf("%I64d",&t);
__int64 st=sqrt(t);//__int64 换成 int 会 wa
if(st*st==t&&prime[st]==0){
puts("YES");
continue;
}
else puts("NO");
}
return 0;
}