Perfect Number In C

吃可爱长大的小学妹 提交于 2021-02-18 12:48:05

问题


I need to write a C program to find the Perfect Number..

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)) - This is d line I do not understand.

If there is any other simple method do please suggest me


回答1:


if(!(num%i)) simply means if( (num%i) == 0 )




回答2:


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.




回答3:


num % i means "num modulo i"; it returns the reminder of the division of the numbers (hence, a number between 0 and i-1).

In C, 0 is false and all other numbers are true, so !(num % i) tests if "num modulo i" is zero, or in plain math-speak, if num is evenly divisible by i.




回答4:


In very simple way, the if(!(num%i)) code checks that if the value of num is divided by i and it returns if remainder is 0 or not...Hence the the modulus operator % is used here to find the remainder.. this piece of code is similar to if(num % i==0). if it returns true then the value of i should be added with sum. Finally if the value of sum is equal to the value of num, the number is perfect and the number is displayed!



来源:https://stackoverflow.com/questions/4554351/perfect-number-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!