PHP program for prime number

We will learn about how to check if a number is prime or not in PHP.

The positive integers having only two factors, 1 and the integer itself are called Prime numbers.  Prime numbers are whole numbers greater than 1.

The first ten primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.

It should be noted that 1 is a non-prime number.

Lets see below example to check number is prime or not using form in php.

Example :

<?php
$result="";
function check_primenum($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}

if(isset($_POST['submit']))
{
$num=$_POST['num'];
$flag = check_primenum($num);
if ($flag== 1)
$result= $num . ' is prime number.';
else
$result= $num . ' is not prime number.';

}

?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Maths Program - Find prime number by aryatechno</title>
</head>
<body>
<table>
<form name="find" method="post">
<tr>
<td colspan="2"><strong>Find prime number program</strong></td>
</tr>
<tr>
<td>Enter Number :</td>
<td><input type="text" name="num" value="<?=$_POST['num'] ?>" required></td>
</tr>

<tr>
<td></td>
<td><input type="submit" value="Find prime number" name="submit" /></td>
</tr>
<tr>
<td colspan="2"><strong><?=$result ?></strong></td>
</tr>

</form>
</table>
</body>
</html>

Output :

Comments

Leave a Reply

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

67576