Squarefree number
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1636 Accepted Submission(s): 438
Problem Description
In mathematics, a squarefree number is one which is divisible by no perfect squares, except 1. For example, 10 is square-free but 18 is not, as it is divisible by 9 = 3^2. Now you need to determine whether an integer is squarefree or not.
Input
The first line contains an integer T indicating the number of test cases.
For each test case, there is a single line contains an integer N.
Technical Specification
1. 1 <= T <= 20
2. 2 <= N <= 10^18
For each test case, there is a single line contains an integer N.
Technical Specification
1. 1 <= T <= 20
2. 2 <= N <= 10^18
Output
For each test case, output the case number first. Then output "Yes" if N is squarefree, "No" otherwise.
Sample Input
2 30 75
Sample Output
Case 1: Yes Case 2: No
思路:题意说的是,给你一个数N,问这个数是否存在因子且该因子是某个整数的平方,若存在则输出No,否则输出Yes.由于N的最大范围达到10^18,这里可以用筛选法得到2-10^6之间的素数,然后依次用小于N的这些数去除N,若某个素数可以除N两次以上,则输出No;否则,若除完2-10^6之间的素数后,N为1则输出Yes;最后若N不为1,则将N开根,得到的数若是整数,输出No,否则输出Yes。简单的原理就是,如果N不存在10^6一下的素数因子,则N必定是大于10^6的数,它可能是某个大于10^6的素数,也可能是大于10^6的某个数的平方(不可能是三次方,也不存在平方后再乘以小于10^6的数,因为之前已经筛选掉了。)
View Code
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <cstring> 5 #include <algorithm> 6 7 using namespace std; 8 9 int prime[1000001]; 10 bool vis[1000001]; 11 12 int main() 13 { 14 memset(vis,0,sizeof(vis)); 15 int idx = 0; 16 for(int i=2; i<=1000; i++) 17 { 18 if(!vis[i]) 19 { 20 for(int j=i*i; j<=1000000; j+=i) 21 vis[j] = true; 22 } 23 24 } 25 for(int i=2; i<=1000000; i++) 26 if(!vis[i]) 27 prime[idx++] = i; 28 int Case; 29 scanf("%d",&Case); 30 for(int ca = 1; ca <= Case; ca ++) 31 { 32 __int64 n; 33 scanf("%I64d",&n); 34 printf("Case %d: ",ca); 35 int time = 0; 36 for(int i=0; i<idx; i++) 37 { 38 time = 0; 39 while(n % prime[i] == 0) 40 { 41 n /= prime[i]; 42 time ++; 43 } 44 if(time >= 2) 45 { 46 break; 47 } 48 } 49 if(time >= 2) 50 { 51 printf("No\n"); 52 continue; 53 } 54 if(n == 1) 55 { 56 printf("Yes\n"); 57 continue; 58 } 59 if(((__int64)sqrt(n*1.0+0.00000001)*(__int64)sqrt(n*1.0+0.00000001)) == n) 60 printf("No\n"); 61 else 62 printf("Yes\n"); 63 } 64 return 0; 65 }