-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathPerfectNumber.php
39 lines (35 loc) · 1.02 KB
/
PerfectNumber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
/**
This function returns true
* if the submitted number is perfect,
* false if it is not.
*
* A perfect number is a positive integer that is
* equal to the sum of its positive proper
* divisors, excluding the number itself.
*
* About perfect numbers: https://en.wikipedia.org/wiki/Perfect_number
*
* @author Marco https://github.com/MaarcooC
* @param int $number
* @return bool
*/
function perfect_number($number)
{
/*Input validation*/
if (!is_int($number) || $number <= 1) {
/*Return false for non-integer or non-positive numbers*/
return false;
}
$divisorsSum = 1; /*1 is a common divisor for every number*/
/*Check for divisors up to the square root of the number*/
for ($i = 2; $i * $i <= $number; $i++) {
if ($number % $i == 0) {
$divisorsSum += $i; /*add i to the sum of divisors*/
if ($i != $number / $i) { /*add the complement divisor*/
$divisorsSum += $number / $i;
}
}
}
return $divisorsSum == $number;
}