How we can check given number is Prime Number or not

Program to check Prime number in PHP

Prime Number: –Hi, readers here in this tutorial we explain that how we can check whether the given number is prime or not using PHP.

Here we start our topic by the logic behind the Prime Number then the simple example with full source code.


The logic to check Prime Number:

In number system, prime numbers are those which is exactly divisible by 1 or itself as well as prime numbers is a whole number greater than 1.

e.g, 2,3,5,7,11,13,17, etc.

Note: 0 and 1 are Non-Prime numbers.

Simple Example:

Here in this example, we create a function to check number. is prime or not

For understanding this example one must have the prior knowledge of if..else structure in php, php operators and how to create php functions . 

In this program first of all the number entered by user is stored in a variable and then creating a function to check prime or not

and  using for loop from 2 to num/2  times as 0 and 1 are a non prime number and then check the condition of prime number if it is divisible by other than itself then comes out of loop using break statement and increment the flag counter which is further used in  if ..else construct

i.e if (flag=-0) evaluates to “true” then print Prime number else if  evaluates to “false” print Non-Prime no.

Full Source Code:

<!Doctype html>
<html>
<head><title>Check prime no. in PHP</title>
</head>
<body>
<!--form is created using post method and submiting values itself -->

<form action="" method="post">
Enter a number:
<input type="text" name="num" />
<input type="submit" value="Check Prime No." />
</form>
<!--end of form-->

<!--php code starts-->
<?php

// if ($_POST) is true i.e.,checking that the HTML form is submited by the method="post" or not.
 if($_POST){
 
/* collecting the value of input field using $_POST['parameter'] 
 and storing it in the variable. */

$num=$_POST['num'];


 function isPrime($num)
 { 
 $orgNum=$num;        //original number is stored in another variable.
 $flag=0;             //flag counter is initialised to 0.
 
 //using for loop from 2 to (num/2) if divisible then come out of loop using break statement
 
 for($i=2;$i<=$num/2;$i++)
 { 
 //condition for non-prime number.
 if(($num%$i)==0)
 { 
 $flag=1;
 break;
 }
 }
 //checking condition of prime no less than or equal to 1
 if($orgNum<=1)
 echo "Given no: $orgNum is not a prime number";


 //checking from 2 to (num-1)
 else if($flag==0) 
 echo "Give Number: $orgNum is a Prime no."; 
 else 
 echo "Given Number: $orgNum is not a prime no.";
 }

//calling the function
 isPrime($num);
 }

?>
<!--php code ends-->

</body>
</html>

Output :

Prime Number

Output of Non-Prime No:

Leave a Comment