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 is divisible by itself only (divisible by 1 natural number, so not a prime number)
- 2 is divisible by itself and also can be divisible by 1 (divisible by 2 natural numbers, so it a prime)
- 3 is also divisible by itself and by 1 (divisible by 2 natural numbers, so it a prime)
- 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 is divisible by itself and by 1 (divisible by 2 natural numbers, so it is a prime number)
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<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:
Thanks. Have a nice day!
How to write a program in PHP for prime numbers, where we should give start number and stop number???