Robson » Code » PHP » Prime Factors

 
<?
   // prime factor finder v1.0
 
   // returns all the prime factors of the specified number
   function prime_factors($number)
   {
       if ($number <= 3)
           $factors = array($number);
       else
       {
           while ($number > 1)
           {
               for ($n = 2; $n < $number && $number % $n; $n++);
               $number /= $n;
               $factors[] = $n;
           }
       }
       return $factors;
   }
   
   // * example use - display prime factors of numbers 0 to 30 * //
   
   for ($n = 0; $n <= 30; $n++)
       echo $n . ' = ' . implode(' * ', prime_factors($n)) . '<br />';
?>    
 
© 2004-17 robson | cc unless stated