题目
一个整数,除了本身以外的其他所有约数的和如果等于该数,那么我们就称这个整数为完全数。
例如,6就是一个完全数,因为它的除了本身以外的其他约数的和为 1+2+3=6。
现在,给定你N个整数,请你依次判断这些数是否是完全数。
输入格式
第一行包含整数N,表示共有N个测试用例。
接下来N行,每行包含一个需要你进行判断的整数X。
输出格式
每个测试用例输出一个结果,每个结果占一行。
如果测试数据是完全数,则输出 X is perfect,其中X是测试数据。
如果测试数据不是完全数,则输出 X is not perfect,其中X是测试数据。
解题思路
首先我们要输入n,并进行n次循环
#include<iostream>
using namespace std;
int main()
{
int n ;
cin >> n;
while(n--){
}
}
接下来,我们进行整数输入,再从1开始到该整数进行遍历,其中条件判断,是否为其公约数,若是,则与计数器相加
#include<iostream>
using namespace std;
int main()
{
int n ;
cin >> n;
while(n--){
int x ,s =0;
cin >> x;
for(int i = 1;i <= x;i++){
if(x % i ==0){
s += i;
}
}
if(s == x)cout << x <<" is perfect" << endl;
else cout << x << " is not perfect" << endl;
}
return 0;
}
但这种做法是有bug的,当x为28时,他得出的结果是28 is not perfect,但1+2+4+7+14=28,得出28是完全数,输出结果和实际不符,还有,若有100个数据进行遍历,计算机运行会超时
我们就换种思路
我们将第二部的for循环条件进行改变,变成小于等于其值的开根
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n ;
cin >> n;
while(n--){
int x ,s =0;
cin >> x;
for(int i = 1;i <= sqrt(x);i++){
if(x % i ==0){
s += i;
}
}
if(s == x)cout << x <<" is perfect" << endl;
else cout << x << " is not perfect" << endl;
}
return 0;
}
其中循环体也将进行更改,我们接下来要进行条件判断,来判断公约值的小值与大值是否相等,同时公约值大值要小于该值,我们将进行公约值大值与计数器相加
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n ;
cin >> n;
while(n--){
int x ,s =0;
cin >> x;
for(int i = 1;i <= sqrt(x);i++){
if(x % i ==0){
s += i;
if(i != x/i&&x/i < x)s += x/i;
}
}
if(s == x)cout << x <<" is perfect" << endl;
else cout << x << " is not perfect" << endl;
}
return 0;
}
但,还会报错 我们就该考虑是否漏了条件
先将x = 1代入上式中,并不是我们所预期的结果
我们漏掉了判断i是否小于x,再进行将i与计数器相加的操作
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n ;
cin >> n;
while(n--){
int x ,s =0;
cin >> x;
for(int i = 1;i <= sqrt(x);i++){
if(x % i ==0){
if(i < x)s += i;
if(i != x/i&&x/i < x)s += x/i;
}
}
if(s == x)cout << x <<" is perfect" << endl;
else cout << x << " is not perfect" << endl;
}
return 0;
}