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 a string d that I do not understand.

If there is any other simple method, please suggest me

+4
source share
4 answers

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

+3
source

If you are looking for a more efficient way to find the perfect rooms, you can read the Wikipedia page on the perfect rooms . In it you will find that unknown odd perfect numbers (and you won’t find using your method) and that all even perfect numbers have the form:

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

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

Note that if you calculate sum this way, this value will be 2 * num for ideal numbers, not num .

+3
source

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

In C, 0 is false and all other numbers are true, therefore !(num % i) checks if the number num modulo i is equal to zero or in the usual mathematical expression if num is evenly divided by i.

+1
source

In a very simple way, the if(!(num%i)) code checks that if the num value is divisible by i and it returns if the remainder is 0 or not ... Therefore, the% module operator is used here to find the remainder .. This snippet The code is similar to if(num % i==0) . if it returns true, then the value i should be added by the sum. Finally, if the sum value is equal to num, the number is ideal and the number is displayed!

0
source

Source: https://habr.com/ru/post/1333668/


All Articles