Saturday, January 3, 2009

Perfect Numbers

This week's function is for checking if an integer is a perfect number.


ASP

  1. function isPerfect(someNumber)
  2.     dim i
  3.     dim arrFactors
  4.     arrFactors = Array()
  5.     ' Only positive integers can be perfect.
  6.     if someNumber < 1 then
  7.         isPerfect = false
  8.         exit function
  9.     end if
  10.     ' Calculate the factors for the given number.
  11.     for i = 1 to someNumber
  12.         if someNumber mod i = 0 then
  13.             redim preserve arrFactors(UBound(arrFactors) + 1)
  14.             arrFactors(UBound(arrFactors)) = i
  15.         end if
  16.     next
  17.     ' A perfect number is a number that is half the sum of all of its positive divisors (including itself).
  18.     if someNumber = eval(join(arrFactors, " + ")) / 2 then
  19.         isPerfect = true
  20.     else
  21.         isPerfect = false
  22.     end if
  23. end function

PHP

  1. function isPerfect($number)
  2. {
  3.     // Only positive integers can be perfect.
  4.     if ($number < 1)
  5.     {
  6.         return false;
  7.     }
  8.     // Calculate the factors for the given number.
  9.     for($i = 1; $i <= $number; $i++)
  10.     {
  11.         if ($number % $i == 0)
  12.         {
  13.             $arrFactors[] = $i;
  14.         }
  15.     }
  16.     // A perfect number is a number that is half the sum of all of its positive divisors (including itself).
  17.     return ($number == array_sum($arrFactors) / 2) ? true : false;
  18. }

No comments: