PHP Script to print Prime Numbers!

In the previous post we saw how to find an Entered number is a Prime number or not!. In this post we are going to print all the Prime numbers.

If you don’t know what is a prime number, here is a small explanations:

  1. 1 is divisible by itself only (divisible by 1 natural number, so not a prime number)
  2. 2 is divisible by itself and also can be divisible by 1 (divisible by 2 natural numbers, so it a prime)
  3. 3 is also divisible by itself and by 1 (divisible by 2 natural numbers, so it a prime)
  4. But, 4 is divisible by itself as well as by 2 and by 1 (divisible by 3 natural numbers, so it is not a prime number)
  5. 5 is divisible by itself and by 1 (divisible by 2 natural numbers, so it is a prime number)
  6. 6 is divisible by itself and by 3 and by 2 and by 1 (so it is divisible by 4 natural numbers, so it is not a prime number)

Now, let’s see the script:

<html>
    <head>
        <title>PHP Script to print prime numbers!</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h2>PHP Script to print Prime numbers!</h2>
        <form method="post">
            Enter the limit:  <input type="number" name="limit" min="0" /><input type="submit" value="Print Prime Numbers" name="print" />
        </form>
    </body>
</html>

<?php
//check if the form is submitted 
if (isset($_POST['print']) && $_POST['print']) {

    $i = $j = 0;
    $limit = $_POST['limit'];

    //loop till $i equals to $limit
    for ($i = 1; $i <= $limit; $i++) {
        $c = 0;
        
        for ($j = 1; $j <= $i; $j++) {
            // % modules will give the reminder value, so if the reminder is 0 then it is divisible
            if ($i % $j == 0) {
                //increment the value of $c
                $c++;
            }
        }

        //if the value of $c is 2 then it is a prime number
        //because a prime number should be exactly divisible by 2 times only (itself and 1)
        if ($c == 2) {
            print $i . "<br>";
        }
    }
}
?>

You can see the demo of the above script here:

demo

Thanks. Have a nice day!

1 thought on “PHP Script to print Prime Numbers!”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top