5

我需要编写一个 C 程序来找到完美数..

main()
{
    int n=1000,sum = 0;
    for(int num = 1; num <= n; num++)
    {
        sum = 0;
        for(int i = 1; i < num; i++)
        {
            if(!(num%i))
            {
                sum+=i;
            }
        }
        if(sum == num)
            printf("\n%d",num);
    }
}

if(!(num%i)) - 这是我不明白的d线。

如果还有其他简单的方法请建议我

4

4 回答 4

3

If you are looking for a more efficient way to find perfect numbers, you might want to read the Wikipedia page on perfect numbers. In it you will find that there are no known odd perfect numbers (and using your method you are not going to find any) and that all even perfect numbers are of the form:

2^(p - 1)*(2^p - 1) where 2^p - 1 is prime and therefore p is a prime. Thus if you want to find even perfect numbers check the primality of 2^p - 1 for all primes p, if so 2^(p - 1)*(2^p - 1) is perfect.

If you just want to find a few small perfect numbers using a simple loop you can make your approach more efficient by noting that if i divides num, so does num / i. That is, you only have to loop up until the square root of num and add pairs i and num / i to sum. Note that if num is square, the square root of num has to be added only once.

Note that if you calculate sum in this way, it's value will be 2 * num for perfect numbers, not num.

于 2010-12-29T13:19:52.680 回答
3

if(!(num%i))只是意味着if( (num%i) == 0 )

于 2010-12-29T13:09:26.567 回答
1

num % i意思是“num modulo i”;它返回数字除法的提醒(因此,一个介于0和之间的数字i-1)。

在 C 中,0 为假,所有其他数字为真,因此!(num % i)测试“num modulo i”是否为零,或者用简单的数学语言来说,如果 num 可以被 i 整除。

于 2010-12-29T13:09:08.317 回答
0

以非常简单的方式,if(!(num%i))代码检查 num 的值是否除以 i,如果余数为 0,则返回...因此,此处使用模运算符 % 来查找余数。这段代码是类似于if(num % i==0)。如果它返回 true,那么 i 的值应该加上 sum。最后如果 sum 的值等于 num 的值,则该数字是完美的并显示数字!

于 2011-12-08T14:36:39.160 回答