用for语句进行查找,while语句进行判断筛选,挺容易的。
直接上代码:
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
for (int a = 2; a <= 1000;a++)
{
int i = 1;
int b = 0;
while (i < a) {
if ((a%i) == 0) b += i;
i++;
}
if (a == b) cout << a << endl;
}
return 0;
}
如果进一步想要输出它的因子的话,只需要将if(a==b)cout<<a<<endl;改成:
if (a == b)
{
cout << a << ": " ;
int c = 1;
while (c<a)
{
if ((a%c) == 0) cout << c << " " ;
c++;
}
cout << endl;
}
即可。也就是在判断一个数为完数后在对这个完数进行输出因子。