题目:
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.
输入:
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, output the case number first. Then output "Yes" if N is squarefree, "No" otherwise.
样例输入:
2
30
75
样例输出:
Case 1: Yes
Case 2: No
题目意思即判断一个数的因子中是否有完全平方数。
暴力搜出所有因子再判断时间花费太多。根据唯一分解定理,即每个数都可以分解为几个质数相乘,我们可以把因子范围缩小到质数,先把质数筛选出来,再用n去除以这些质数,如果能被同一个质数整除两次,即因子中有完全平方数。这里要注意n的范围是10的18次方,而筛选出这么大范围的质数不怎么行(数组大小限制,时间花费也多),所以我们只需筛选出10的6次方以内的质数,拿n去除,最后的n只会有两种情况,一种是等于一,即所有因子都小于10的6次方,另一种是大于10的6次方,说明有大于10的6次方的质因子,而这样的因子的指数最多为2(这里n有三种情况,质数,质数乘另一个质数,质数的平方),接下来只需开平方验证是否是完全平方数即可。
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int vis[1000005]={1,1};
long long prime[1000005]={0};
int sum=0;
void shai()
{
for(int i=2;i<1000005;i++)
if(!vis[i]){
prime[sum++]=i;
for(long long j=(long long)i*i;j<=1000005;j+=i)
vis[j]=1;
}
}
int main()
{
ios::sync_with_stdio(false);
int t,cou=1;
shai();
cin>>t;
while(t--)
{
long long n;
int flag=0;
cin>>n;
for(int i=0;i<sum;i++)
{
if(n%prime[i]==0)
{
n/=prime[i];
if(n%prime[i]==0)
{
flag=1;break;
}
}
}
if(n>1000000)
{
int m=(int)sqrt(n);
if((long long)m*m==n)
flag=1;
}
cout<<"Case "<<cou++<<": ";
if(flag==1)
cout<<"No\n";
else cout<<"Yes\n";
}
return 0;
}