PHP program to check if a number is prime or not

PHPServer Side ProgrammingProgramming

To check if a number is prime or not, the code is as follows −

Example

 Live Demo

<?php
function check_prime($num)
{
   if ($num == 1)
   return 0;
   for ($i = 2; $i <= $num/2; $i++)
   {
      if ($num % $i == 0)
      return 0;
   }
   return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
   echo "It is a prime number";
else
   echo "It is a non-prime number"
?>

Output

It is a prime number

A function named ‘check_prime’ is used to check if the number is prime or not. A number that needs to be checked for being prime is passed as a parameter to the function. The number is defined and this function is called by passing the number as parameter. Relevant message is displayed on the console.

raja
Published on 02-Jul-2020 06:55:06
Advertisements