w3resource
php Programming Exercies

PHP Exercises: Print the number of prime numbers which are less than or equal to a given integer

PHP: Exercise-52 with Solution

Write a PHP program to print the number of prime numbers which are less than or equal to a given integer.

Input:
n (1 ≤ n ≤ 999,999) .

Pictorial Presentation:

PHP: Print the number of prime numbers which are less than or equal to a given integer.

Sample Solution: -

PHP Code:

<?php
 $max = 1000000;
  
// Initialize the array.
for ($i = 0; $i <$max; $i ++) {
    $array [$i] = 1;
}
$array [1] = 0;
  
// Since 0 and 1 are not prime numbers, search starts from 2
for ($i = 2; $i<$max; $i ++) {
  if ($array [$i] === 0)
    // If the start value has been sifted out, that multiple
    continue;
  else
    {
    For ($j = $i * $i; $j<$max; $j += $i) {
      $array [$j] = 0;
    }
}
  
for ($i = 2; $i <$max; $i ++) {
  $array [$i] += $array [$i-1];
}
  
While (1) {
  $res = fscanf(STDIN, '%d', $n);
  if ($res == 0) break;
  
  $cnt = $array [$n];
  // output
  echo "Number of prime numbers which are less than or equal to n: ";
  echo $cnt.PHP_EOL;
}
}
?>

Sample Output:

Number of prime numbers which are less than or equal to n: 618

Flowchart:

Flowchart: Print the number of prime numbers which are less than or equal to a given integer.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to compute the amount of the debt in n months.
Next: Write a PHP program to compute the radius and the central coordinate (x, y) of a circle which is constructed by three given points on the plane surface.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming