Posted By

Scooter on 01/03/09


Tagged

math


Versions (?)

Perfect Numbers


 / Published in: PHP
 

URL: http://reusablecode.blogspot.com/2009/01/perfect-numbers.html

Determine whether the given number is a perfect number.

  1. <?php
  2. /*
  3.   Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.
  4.  
  5.   This work is licensed under the Creative Commons Attribution License. To view
  6.   a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  7.   send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  8.   94305, USA.
  9.   */
  10.  
  11. // Determine whether the given number is a perfect number.
  12. function isPerfect($number)
  13. {
  14. // Only positive integers can be perfect.
  15. if ($number < 1)
  16. {
  17. return false;
  18. }
  19.  
  20. // Calculate the factors for the given number.
  21. for($i = 1; $i <= $number; $i++)
  22. {
  23. if ($number % $i == 0)
  24. {
  25. $arrFactors[] = $i;
  26. }
  27. }
  28.  
  29. // A perfect number is a number that is half the sum of all of its positive divisors (including itself).
  30. return ($number == array_sum($arrFactors) / 2) ? true : false;
  31. }
  32. ?>

Report this snippet  

You need to login to post a comment.