c语言一个数如果恰好等于它的因子之和,这个数就称为完数。例如,6的因子是1,2,3,而6=1+2+3,因此6为完数。编程序找出1000之内所有的完数,并按下列格式输出其因子:6 its factors are 1,2,3
时间: 2024-05-16 13:18:21 浏览: 90
下面是用 C 语言编写的程序,可以找出1000之内所有的完数,并输出其因子:
```c
#include <stdio.h>
int main()
{
int i, j, sum;
printf("The perfect numbers between 1 and 1000 are:\n");
for (i = 1; i <= 1000; i++) {
sum = 0;
for (j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
printf("%d its factors are ", i);
for (j = 1; j < i; j++) {
if (i % j == 0) {
printf("%d ", j);
}
}
printf("\n");
}
}
return 0;
}
```
输出结果如下:
```
The perfect numbers between 1 and 1000 are:
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
```
这个程序遍历了1到1000之间的所有数字,对于每个数字,它计算出该数字的所有因子之和,如果和等于该数字本身,则输出该数字及其因子。
阅读全文