Posted By

mscribellito on 02/25/11


Tagged


Versions (?)

Compute Prime Factorization of N


 / Published in: PHP
 

  1. function factors($n = 0, $array = FALSE) {
  2.  
  3. $pf = array();
  4. for ($i = 2; $i <= $n / $i; $i++) {
  5. while ($n % $i == 0) {
  6. $pf[] = $i;
  7. $n = $n / $i;
  8. }
  9. }
  10.  
  11. if ($n > 1) $pf[] = $n;
  12. return ($array === TRUE) ? $pf : implode(' * ', $pf);
  13.  
  14. }
  15.  
  16. echo factors(55);
  17.  
  18. // 5 * 11
  19.  
  20. print_r(factors(55, true));
  21.  
  22. // Array ( [0] => 5 [1] => 11 )

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: iamdezzy on February 28, 2011

I don't get it. How it works? When I printed something like factors(55) it just says "array".

Posted By: mscribellito on May 4, 2011

I edited the code.

calling factors(55) would return "5 * 11"

calling factors(55, true) would return an array of the factors ex: Array ( [0] => 5 [1] => 11 )

You need to login to post a comment.