【完数】
以下程序功能是实现求10000 以内的自然数中的完数及其个数(所谓完数,指它恰好等于除它本身之外的因子之和,如:6=1+2+3,28=1+2+4+7+14),并显示结果。
Talk is cheap, show me the code.
#include <stdio.h>
#define LEN 10000
int main(void)
{
int i, k, m, n, s, p=0;
int a[100]; //存放各个因子
printf("Number as follows:");
for (i=2; i<= LEN; i++)
{
s = 0; //计算因子和
m = 0;
k = 1;
while (k <= i/2) //因为不算自身,所以剩余因子肯定<=i/2
{
if (i % k == 0) //如果k是i的因子
{
s += k;
a[m] = k;
m ++;
}
k ++;
}
if (s == i) //因子和 等于 数本身
{
p ++;
printf("\n%d\t= %d", s, a[0]);
n = 1;
while (n < m)
{
printf(" + %d", a[n]);
n ++;
}
}
}
printf("\nTotal Num: %d", p);
return 0;
}