Primality Tester

From MFSP Wiki

Jump to: navigation, search

The script for the current primality tester is:

<?php

function Primality ($num) {

     if($num < 2) {
          $result = "$num is not prime.";
     } elseif($num == 2) {
          $result = "$num is prime!";
     } elseif(bcmod($num, 2) == 0 && $num != 2) {
          $result = "$num is not prime. It is divisible by 2.";
     } else {
          $lim = (bcsqrt($num));

          for($i = 3; $i <= $lim; $i+=2) {
               if(bcmod($num, $i) == 0){
                    $result = "$num is not prime. It is divisible by $i.";
                    break;
               }
          }

          if (!isset($result)) {
               $result = "$num is prime!";
          }
     }

     return $result;

}
?>

This primality tester will be bundled as part of the Expression Evaluator (Command "p-> x <-"). If you can find any further optimizations (Without resorting to a probabilistic program), please contact me.

As with all scripts here, if you re-distribute the code, I ask that you simply include the following comments beforehand:

# Script by Andre Kessler for MathForSmartyPants.com, some rights reserved. 
# See http://creativecommons.org/licenses/by-nc-sa/3.0/ for more info.
# Please leave these comments in the script if you re-distribute them.
Personal tools