This week's function is for checking if an integer is a perfect number.
ASP
function isPerfect(someNumber)
dim i
dim arrFactors
arrFactors = Array()
' Only positive integers can be perfect.
if someNumber < 1 then
isPerfect = false
exit function
end if
' Calculate the factors for the given number.
for i = 1 to someNumber
if someNumber mod i = 0 then
redim preserve arrFactors(UBound(arrFactors) + 1)
arrFactors(UBound(arrFactors)) = i
end if
next
' A perfect number is a number that is half the sum of all of its positive divisors (including itself).
if someNumber = eval(join(arrFactors, " + ")) / 2 then
isPerfect = true
else
isPerfect = false
end if
end function
PHP
function isPerfect($number)
{
// Only positive integers can be perfect.
if ($number < 1)
{
return false;
}
// Calculate the factors for the given number.
for($i = 1; $i <= $number; $i++)
{
if ($number % $i == 0)
{
$arrFactors[] = $i;
}
}
// A perfect number is a number that is half the sum of all of its positive divisors (including itself).
return ($number == array_sum($arrFactors) / 2) ? true : false;
}
No comments:
Post a Comment