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
.
42
? :) And you wrote code that you don't understand? How come? – Debaucheeif not remainder of num / i
. – Grimy