A natural number is perfect, if it's value is equal to a sum of all his positive divisors (excluding number itself). The first perfect numbers are 6, 28, 496, 8128 and all of them are in form . Greek mathematician Euclid proved that the formula is en even perfect number whenever is a prime.
So far only even perfect numbers have been discovered, but the existence of odd perfect numbers was never disproved. According to the current state of knowledge, the odd perfect number must be higher than .
Examples
Code
/** * Checks whether the number is perfect * @param number tested number * @return true if the number is perfect, false otherwise */ public static boolean isPerfect(long number) { //odd perfect number (probably) does not exist, and even if it does, it has a higher value than long can represent if (number % 2 == 1) { return false; } long result = 1; //1 is a trivial divisor long i = 2; while (i * i <= number) { //until i <= sqrt(number) if (number % i == 0) { result += i; result += number / i; } i++; } if (i * i == number) { //perfect square, sqrt(number) was added twice result -= i; } return result == number; }
/** * Checks whether the number is perfect * @param $number tested number * @return true if the $number is perfect, false otherwise */ function isPerfect($number) { if ($number % 2 == 1) { return false; } $result = 1; //1 is a trivial divisor $i = 2; while ($i * $i <= $number) { //until i <= sqrt(number) if ($number % $i == 0) { $result += $i; $result += $number / $i; } $i++; } if ($i * $i == $number) { //perfect square, sqrt(number) was added twice $result -= $i; } return $result == $number; }