Open In App

PHP Program to Print Prime Number from 1 to N

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to print all prime numbers in a range from 1 to N in PHP.

Examples:

Input: N = 10
Output: 2, 3, 5, 7

Input: N = 50
Output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Print Prime Numbers using PHP for Loop

  • First, take the number N as input.
  • Then use a for loop to iterate the numbers from 1 to N
  • Then check for each number to be a prime number. If it is a prime number, print it.

Example:

PHP




<?php
  
function isPrime($n) {
    if ($n == 1 || $n == 0) {
        return false;
    }
  
    // Run a loop from 2 to sqrt(n)
    for ($i = 2; $i <= sqrt($n); $i++) {
        if ($n % $i == 0) {
            return false;
        }
    }
  
    return true;
}
  
// Driver code
$N = 50;
  
// Check for every number from 1 to N
for ($i = 1; $i <= $N; $i++) {
    if (isPrime($i)) {
        echo $i . " ";
    }
}
?>


Output

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

Print Prime Numbers using Optimized Brute Force

This approach optimizes the brute force method by avoiding redundant checks.

Example:

PHP




<?php
function isPrime($number) {
    if ($number < 2) {
        return false;
    }
  
    if ($number == 2 || $number == 3) {
        return true;
    }
  
    if ($number % 2 == 0 || $number % 3 == 0) {
        return false;
    }
  
    $i = 5;
    $w = 2;
  
    while ($i * $i <= $number) {
        if ($number % $i == 0) {
            return false;
        }
  
        $i += $w;
        $w = 6 - $w;
    }
  
    return true;
}
  
function printPrimes($N) {
    for ($i = 2; $i <= $N; $i++) {
        if (isPrime($i)) {
            echo $i . " ";
        }
    }
}
  
// Driver code
$N = 50;
  
printPrimes($N);
  
?>


Output

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads