#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n ;
while(n--)
{
int x = 0,sum = 0;
cin >> x;
for( int i = 1; i * i <= x; i++)
{
if( x%i == 0 )
{
if(i<x) sum += i;
if(i != x/i && x/i < x) sum += x/i;
}
}
if (sum == x) cout<< x <<" is perfect"<<endl;
else cout<< x <<" is not perfect"<<endl;
}
return 0;
}
也可以先考虑1的值,因数是成对存在的,可以对x进行开方,求出前一半的因数i,那后一半的可以用x/i求出来。前一半中包含1,那么后一半中就包含他本身,所以sum求完以后要减去它本身,这样在与x进行比较.这样写的好处是不会超时。
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int n,x;
cin>>n;
int s;
int sum;
while(n--)
{
cin>>x;
sum=0;
if(x==1)
cout<<x<<" is not perfect"<<endl;
else
{
for(int i=1;i<=sqrt(x);i++)
if(x%i==0)
{
sum+=i;
s=x/i;
//printf("%d %d\n",i,s);
sum+=s;
}
//printf("%d\n",sum);
if(sum/2==x)
cout<<x<<" is perfect"<<endl;
else
cout<<x<<" is not perfect"<<endl;
}
}
return 0;
}