Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top