Q:

Prime Number in php

belongs to collection: PHP Programs

0

A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7, 11, 13, 17, etc. are prime numbers.

  • 2 is the only even prime number.
  • It is a natural number greater than 1 and so 0 and 1 are not prime numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Prime number in PHP

Example:

Here is the Program to list the first 15 prime numbers.

<?php  
$count = 0;  
$num = 2;  
while ($count < 15 )  
{  
$div_count=0;  
for ( $i=1; $i<=$num; $i++)  
{  
if (($num%$i)==0)  
{  
$div_count++;  
}  
}  
if ($div_count<3)  
{  
echo $num." , ";  
$count=$count+1;  
}  
$num=$num+1;  
}  
?>  

Output:

Prime Number using Form in PHP

Example:

We'll show a form, which will check whether a number is prime or not.

<form 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';  
   }   
}  
?>  

Output:

On entering number 12, we get the following output. It states that 12 is not a prime number.

On entering number 97, we get the following output. It states that 97 is a prime number.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Table of Number in Php... >>
<< Even Odd Program in Php...