Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfect Number In C

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

like image 347
Harish Avatar asked Dec 29 '10 13:12

Harish


2 Answers

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

like image 115
ykatchou Avatar answered Nov 01 '22 17:11

ykatchou


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.

like image 35
heijp06 Avatar answered Nov 01 '22 18:11

heijp06