Robson » Code » PHP » Smallest Divisor

 
<?
   // find smallest divisor v1.0
 
   // returns the smallest number that divides exactly into the number specified
   // tip: combine with a prime number generator to speed up results
   function smallest_divisor($number)
   {
       // loop from two to just before the number specified
       // only loop while the division operation isn't whole
       for ($n = 2; $n < $number && $number % $n; $n++);
       // return the smallest divisor
       return $n;
   }
   
   // * example use - show smallest divisors of first twenty numbers * //
   
   // loop from 1 to 20
   for ($n = 1; $n <= 20; $n++)
       // show the smallest divisor for each
       echo $n . ' = ' . smallest_divisor($n) . '<br />';
?>    
 
© 2004-17 robson | cc unless stated