February 5, 2013

PHP code for prime number detection

Find Prime number using PHP code


Here is the procedure the determine if a number is prime or not. I will code it using PHP, but let me show you the algorithm first so that you can rewrite it using any language.

Algorithm:
1. Take the number to be decided as a variable "i"
2. If the number is 1 or 2, it is prime. So flag it as prime under a variable "flag_one". If this variable is TRUE, we will declare the number as prime.
3. If the number is completely divisible by 2, it is an even number and is not prime. Flag it as false in this case.
4. If the number is not divisible by 2 (and not equals to 1, handled in step two), it must be odd. Now we need to check if the number is divisible by any number which is lower in value than the input number. Actually it will suffice to check any number less than half of the input number. For example, if the input number is 17, we need to check untill 17/2=8.5, rounded to 9 and check if 17 is completely divisible by any number starting from 3 to 9. If it is, we do not need to check it any further and declare it as prime under the variable "flag_one". If not, we need to check it untill 9. Finally, if we do not find any number that divides the input with a remainder zero we need to declare the input as NOT prime.

Code:



 <?php

 $i=3561;
   if ($i==1 || $i==2) $flag_one=true;
     elseif ($i%2==0) $flag_one=false;
       else
        {

           $j=ceil($i/2)-1;

            for ($k=3;$k<=$j;$k++)
               {
 
                 if ($i%$k==0) {$flag_one=false;break;}
 
                else $flag_one=true;
                }

        }

        if ($flag_one) echo $i." is Prime";
        else echo $i." is NOT Prime";
 ?>

You can run the code directly at: http://codepad.org/xQOxDrVd

The code is tested with wikipedia list of prime numbers, located at http://en.wikipedia.org/wiki/List_of_prime_numbers . If you find anything wrong with the code or algorithm, let me know on the comment.