PHP Program - Find all Prime Numbers in a given Interval


Advertisements

A Prime number is a natural number greater than $$1$$ and divisible by $$1$$ and itself only, for example $$- 2, 3, 5, 7,$$ etc.

Objective: Write a PHP code to find all prime numbers in a given internal.

Example: Using function to find prime number

In the below example, a function called primenumber() is created which takes a number as argument and checks it for prime number by dividing it with all natural numbers starting from $$2$$ to $$\frac{N}{2}$$.

<?php

  function primenumber($MyNum) {
    $n = 0;
    for($i = 2; $i < ($MyNum/2+1); $i++)
    {
      if($MyNum % $i == 0){
        $n++;
        break;
      }
    }
    if ($n == 0){
      echo $MyNum." ";
    } 
  }

  $x = 10;
  $y = 50;
  echo "Prime numbers between ".$x." and ".$y." are: \n";
  for($i = $x; $i < $y + 1; $i++)
  {
    primenumber($i);
  }
?>

Output

Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47

Example: Optimized Code

  • Instead of checking the divisibility of given number from $$2$$ to $$\frac{N}{2}$$, it is checked till $$\sqrt{N}$$. For a factor larger than $$\sqrt{N}$$, there must the a smaller factor which is already checked in the range of $$2$$ to $$\sqrt{N}$$.
  • Except from $$2$$ and $$3$$, every prime number can be represented into $$6k\pm1$$.

<?php

  function primenumber($MyNum) {
    $n = 0;
    if ($MyNum == 2 || $MyNum == 3){
      echo $MyNum." ";
    } elseif ($MyNum % 6 == 1 || $MyNum % 6 == 5) {
        for($i = 2; $i*$i <= $MyNum; $i++)
        {
          if($MyNum % $i == 0){
            $n++;
            break;
          }
        }
        if ($n == 0){
          echo $MyNum." ";
        } 
    } 
  }

  $x = 100;
  $y = 200;
  echo "Prime numbers between ".$x." and ".$y." are: \n";
  for($i = $x; $i < $y + 1; $i++)
  {
    primenumber($i);
  }
?>

Output

Prime numbers between 100 and 200 are:
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 




Advertisements