任务是:
编写一个程序,计算输入数字的除数之和。
如果一个数字的除数之和等于该数字,则该数字被视为完美数字(例如:6 = 1+2+3;28 = 1 + 2 + 4 + 7 +14)。
另一个定义: 完美数是其所有正因数(包括其自身)之和的一半的数
生成前 k 个完全数 (k<150)。
这样做的主要问题是,这两个问题并不真正相关,这让人感到困惑。
在这个程序中,我计算了输入数字的除数之和,但我不知道如何将其与第二点联系起来(生成前 k 个完美数字 (k<150))。
#include <stdio.h>
#include <stdlib.h>
main()
{
int x,i,y,div,suma,k;
printf("Introduceti numarul\n"); \\enter the number
scanf("%d",&x);
suma=0; \\sum is 0
for(i=1;i<=x;i++)
{
if(x%i==0)
suma=suma+i; \\sum=sum+i;
}
printf("Suma divizorilor naturali este: %d\n",suma); \\the sum of the divisors is
for(k=1;k<150;k++) \\ bad part
{
if (x==suma)
printf("%d",k);
}
}
最佳答案
假设你有一个函数可以判断给定的整数是否完美:
int isPerfect(int);
(函数体未显示)
现在你的主程序将如下所示:
int candidate;
int perfectNumbers;
for(candidate = 1, perfectNumbers = 0; perfectNumbers < 150; candidate++) {
if (isPerfect(candidate)) {
printf("Number %d is perfect\n", candidate);
perfectNumbers++;
}
}
编辑 对于没有函数的同一个程序:
int candidate;
int perfectNumbers;
for(candidate = 1, perfectNumbers = 0; perfectNumbers < 150; candidate++) {
[... here your algorithm to compute the sum of the divisors of "candidate" ...]
if (candidate*2 == sum_of_divisors) {
printf("Number %d is perfect\n", candidate);
perfectNumbers++;
}
}
编辑2:只是关于完美数字的注释
正如下面的评论部分所述,完美数非常罕见,截至 2014 年只有 48 个已知。序列 ( A000396 ) 也增长得非常快:使用 64 位整数,您将能够计算第 8 个完全数(恰好是 2,305,843,008,139,952,128)。在这种情况下,变量 candidate
将环绕并从头开始“查找”"new"完美数(直到找到其中 150 个:实际上 64 位整数中唯一可找到的 8 个数的 19 次重复)。但请注意,您的算法不得因 candidate
等于 0
或负数(仅在您声明 candidate 时为
为 0
)而阻塞unsigned int
)。
关于c - 关于除数和和完美数的棘手且令人困惑的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26786980/