Hello friends, Let’s see another School / College program that is useful for understanding the basic concepts of PHP.

And the PHP script what we are going to see is “Find the Prime numbers”.

If you already don’t know what is a Prime number, I will give you some example:

A prime number is a number that is divisible only by itself and 1.

For Eg:

**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)**

Let’s see the scrip first:

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<?php //here is the function to find prime number //this function return true if the number is prime function find_prime($num) { $res = false; $i = $c = 0; //loop till $i equals to $num for ($i = 1; $i <= $num; $i++) { //check if the $num is divisible by itself and 1 // % modules will give the reminder value, so if the reminder is 0 then it is divisible if ($num % $i == 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) { $res = true; } return $res; } ?> <html> <head> <title>PHP Script to find prime number or not!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>PHP Script to find Prime number or not!</h2> <form method="post"> Enter a number: <input type="number" name="num" min="0" /><input type="submit" value="Find Prime Number" name="find" /> </form> </body> </html> <?php //check if the form is submitted if (isset($_POST['find']) && $_POST['find']) { $num = $_POST['num']; //call the find_prime() function $prime = find_prime($num); //if the $prime value is true, then the result is a Prime number if ($prime) { print "<b>" . $num . "</b> is a Prime number."; } else { print "<b>" . $num . "</b> is not a Prime number."; } } ?> |

You can read the comments in the above script to understand how the script works!

See the demo here:

Adios!

thank you very very very much I did not find this anywhere.