PHP Program to check whether the number is prime or composite

What is a Prime Number & Composite Number?

Prime numbers are natural numbers that are greater than 1 that are not a product of two smaller natural numbers.  Prime numbers are natural numbers that are greater than 1 that are not a product of two smaller natural numbers. Composite numbers are natural numbers greater than 1 and which are not prime numbers. For example, 7 has no divisors other than 1 and 7 itself which is a prime number and   has more than two divisors which is a composite number. 

How to Check Whether the Number is Prime or Composite in PHP?

In PHP to check whether the number is Prime or Composite by using Mod(%) Operator. We have used a user-defined function to check the number and the user entered number will be passed as an argument and it first checks whether it is greater than 1 or not. If it is 1 it will directly return 0 or else check for whether the number can be perfectly divisible by other numbers less than the number itself by the operation (num % i == 0). If it is then it will return otherwise it will return 1 from the function check_num().

ALGORITHM

Step 1: Accept the number into the variable num

Step 2: Create a variable flag to assign the return value from the user-defined function check_num() with argument num

Step 3: By using the if statement check the condition if the value of the variable flag is 1 if true print the 'It is a prime number' otherwise print 'It is a  composite number' using the function echo.

ALGORITHM User define function : check_num(num)

Step 1: check for the num is 1 by using the if statement if true return 0 as the result of the function check_num() and exit otherwise perform the following steps.

Step 2: Perform the for loop and assign the value 2 into variable i and perform the sub-step until the condition 'i <= num / 2' becomes false and increment the value of variable i in every iteration

            (i) check the condition 'num % i == 0' it true return 0 as the result of the function check_num()

Step 3: return 1 as the result of the function check_num()

 

PHP Source Code

                                          <?php
function check_num($num)
{
    if ($num == 1)
        return 0;
    for ($i = 2; $i <= $num / 2; $i++) {
        if ($num % $i == 0)
            return 0;
    }
    return 1;
}
$num = readline("Enter the number: ");
$flag = check_num($num);
if ($flag == 1)
    echo "It is a prime number";
else
    echo "It is a composite number";
?>
                                      

OUTPUT

Example 1
Enter the number: 1
It is a composite number

Example 2
Enter the number: 79
It is a prime number

Example 3
Enter the number: 56
It is a composite number