Squarefree number
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2754 Accepted Submission(s): 695
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
Author
hanshuai
Source
Recommend
有一个理论就是所有的数都能分解成质因数相乘,所以直接判断能不能被某个质数的平方相除就好了,但是这个N是18次方。所以在判断大数的时候,如果她能被哪个小于10的7次的质数整除就除下来,这样子在暴力完10的7次方内质数的时候,这个N整个就已经变小了很多,然后再判断它自己是不是个完全平方数就可以了,应为它如果不是质数,就已经从18次方被除下来了,假设降到12次方,可是判断平方的时候,12次方是6次方的平方,如果不是质数就一定也在第一步被整除掉了,所以最后只需要判断自己是不是完全平方数就可以了。
还有一个注意点就是跳出循环的条件,要避免prm[I]等于N的时候。
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
long long prm[1000010];
const int MAXV = 1e7;
bool isPrime[MAXV+1];
int size=0;
void getPrime()
{
memset(isPrime, true, sizeof(isPrime));
int sq = sqrt((double)MAXV) + 1;
int i,j,k;
for(i = 2;i <= sq; i++)
if(isPrime[i])
for(j = 2,k = MAXV/i+1;j < k;j++)
isPrime[i*j] = false;
for( i = 2 ; i <= MAXV; i++)
if(isPrime[i])
prm[size++] = i;
isPrime[0] = isPrime[1] = false;
}
int main(){
getPrime();
int t;
scanf("%d",&t);
int sjy = 1;
while(t--)
{
long long n;
scanf("%lld",&n);
int ok = 0,ans = 1;
for (int i = 0; i < size && prm[i] < n; i++)
{
if (n % prm[i] == 0)
{
n /= prm[i];
if (n % prm[i] == 0)
{
ans = 0;
break;
}
}
}
if (ans)
{
double temp = sqrt(n * 1.0);
if ((int)(temp + 0.5) == temp) ans = 0;
else ans = 1;
}
if (!ans) printf("Case %d: No\n",sjy++);
else printf("Case %d: Yes\n",sjy++);
}
return 0;
}