PHP Examples

PHP Program - Find all Prime Numbers less than the given Number



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 less than a given number.

Method 1: Using method to find prime number

In the example below, a method 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 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 = 50;
echo "Prime numbers less than ".$x." are: \n";
for($i = 2; $i < $x + 1; $i++) {
  primenumber($i);
}
?>

The above code will give the following output:

Prime numbers less than 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

Method 2: Optimized Code

  • Instead of checking the divisibility of given number from 2 to N/2, it is checked till square root of N. For a factor larger than square root of N, there must the a smaller factor which is already checked in the range of 2 to square root of N.
  • Except from 2 and 3, every prime number can be represented into 6k ± 1.
<?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;
echo "Prime numbers less than ".$x." are: \n";
for($i = 2; $i < $x + 1; $i++) {
  primenumber($i);
}
?>

The above code will give the following output:

Prime numbers less than 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97