用C语言一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如,6的因子为1,2,3,且6=1+2+3,因此6是“完数”。编程找出1000之内的所有完数,按如下格式输出其因子:6 its factors are 1 2 3
时间: 2023-07-14 20:12:47 浏览: 72
C语言程序设计-计算并输出给定整数n的所有因子之和(不包括1与自身);注意:n的值不大于1000.c
5星 · 资源好评率100%
以下是C语言代码实现:
```c
#include <stdio.h>
int main() {
int i, j, sum;
printf("Perfect numbers within 1000: \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;
}
```
运行结果如下:
```
Perfect numbers within 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
```
阅读全文