 # PHP Program to check whether the number is prime or composite

February 4, 2022, Learn eTutorial
1374

## What is a Prime Number & Composite Number?

The Prime number is an integer with no other positive divisors other than 1 and that number itself. Natural numbers other than the prime number are called the Composite number.

For example, 2, 3, 5, 7, 11, 13, etc are prime numbers because they have only 2 divisors and the number '4', '6', which have more than two divisors are composite numbers.

Let us take an example as the number '5' is a prime number because the number '5' has only two divisors: '1' and '5'. So the prime number has two divisors only. But, 4 is not prime (it is composite) since 2 x 2 = 4.

## 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

```                                          ```<?
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```