用C语音实现找出1~1000 内的所有完数,并按以下格式输出,6 its factors are 1,2,3。
时间: 2024-04-29 19:25:30 浏览: 52
完数是指一个数恰好等于它的因子之和,例如6是完数,因为6的因子为1、2、3,且1+2+3=6。
以下是用C语言实现找出1~1000内的所有完数,并按照题目要求输出的代码:
```c
#include <stdio.h>
int main()
{
int i, j, sum;
printf("Perfect numbers between 1 and 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("\b.\n"); // 去掉最后一个逗号
}
}
return 0;
}
```
运行结果:
```
Perfect numbers between 1 and 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.
```
阅读全文