赞
踩
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 n space-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 %I64d specifier.
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".
解题说明:此题就是判断一个数是否仅含有3个因子,其实也就是除了1和它自身外,还存在另一个因子。如果找到这个另外的因子就输出yes,否则为no。
首先来分析这个数的情况,由于只有一个不同的因子,那这个数肯定是某个数的平方数,否则不可能只有一个因子。这样问题缩小为在2到n^(1/2)-1之间求因子的个数,如果因子个数不为0,那证明还存在其他因子,不符合题意,我们就证明其中不存在因子即可,问题进一步转换为证明n^(1/2)是个素数。
证明素数的问题很常见,令m=n^(1/2),然后判断m^(1/2)之间有没有因子即可。
- #include<cstdio>
- #include<iostream>
- #include<algorithm>
- #include<cstring>
- #include<cmath>
- using namespace std;
-
- int main()
- {
- int n,i,j;
- long long a,b;
- cin>>n;
- for(i=1;i<=n;i++)
- {
- cin>>a;
- b=sqrtl(a); //long double sqrtl( long double x );
- for(j=2;j*j<=b;j++)
- {
- if(b%j==0)
- {
- break;
- }
- }
- if(j*j>b && b*b==a && a>1)
- {
- cout<<"YES\n";
- }
- else
- {
- cout<<"NO\n";
- }
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。