In this tutorial, we would love to share with you how to check whether a given number is prime or not.
What is Prime Number?
Answer: A number that is only divisible by 1 and itself is called a prime number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
How to Check Prime Number in PHP?
Here is the php program that can check whether a given number is prime or not.
<?php function IsPrimeOrNot($n) { for($i=2; $i<$n; $i++) { if($n % $i ==0) { return 0; } } return 1; } // Pass The Number For check it is prime or not $a = IsPrimeOrNot(5); if ($a==0) echo 'This is not a Prime Number.....'."\n"; else echo 'This is a Prime Number..'."\n"; ?>
Prime Number using Form in PHP
To check whether a given number in form is prime or not in php:
<html> <head> <title>Prime Number using Form in PHP</title> </head> <body> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> Enter a Number: <input type="text" name="input"><br><br> <input type="submit" name="submit" value="Submit"> </form> <?php if($_POST) { $input=$_POST['input']; for ($i = 2; $i <= $input-1; $i++) { if ($input % $i == 0) { $value= True; } } if (isset($value) && $value) { echo 'The Number '. $input . ' is not prime'; } else { echo 'The Number '. $input . ' is prime'; } } ?> </body> </html>