打印完数
描述
一个数如果恰好等于它的因子之和,这个数就成为“完数”。例如,6的因子为1、2、3,而6=1+2+3,因此6是“完数”。
编程序打印出1000之内(包括1000)所有的完数,并按如下格式输出其所有因子:6 its factors are 1,2,3
输入
无输入
输出
输出1000以内所有的完数及其因子,每行一个完数。
样例输入
(无)
样例输出
6 its factors are 1,2,3
28 its factors are 1,2,4,7,14
496 its factors are 1,2,4,8,16,31,62,124,248
源代码
#include<iostream>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
int h(int a)
{
int b, c[1000] = { 0 }, d = 0;
for (b = 1; b <= a / 2; b++)
{
if (a % b == 0)
{
c[d] += b;
}
}
return c[d];
d++;
}
int main()
{
int i, j, sum = 0;
for (i = 1; i <= 1000; i++)
{
sum = h(i);
if (i == sum)
{
cout << i << " " << "its factors are 1"; //因子必含1
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
cout << "," << j;
}
}
cout << endl;
}
}
}