PHP Program to check whether a number is perfect square or not


May 8, 2022, Learn eTutorial
1222

How to check whether a number is a perfect square or not using PHP?

In this program, we are using the built-in functions sqrt() and floor() to check the number is a perfect square or not. For that, we first have to accept the value from the user and assign it to the variable num. Then find the square of the variable num using the built-in function sqrt(sr) and assign the result into the variable sr and assign the computed value of 'sr - floor(sr)' into the variable sr. And at last, we have to check the condition 'sr == 0' if true print the value of the variable num as the perfect square number otherwise print the value of the variable num as not the perfect square number.

Syntax


sqrt(number);
floor(number);
 

ALGORITHM

Step 1: Accept the value from the user and assign it to the variable num

Step 2: Find the square of the variable num using the built-in function sqrt() and assign the result into the variable sr

Step 3: Assign the computed value of 'sr - floor(sr)' into the variable sr

Step 4: Check the condition 'sr == 0' if true print the value of the variable num as the perfect square number otherwise print the value of the variable num as not the perfect square number

PHP Source Code

                                          <?php
$num = readline("Enter the number: ");
$sr = sqrt($num);
$sr = ($sr - floor($sr));
if ($sr == 0)
    echo "The entered number $num is a perfect square";
else
    echo "The entered number $num is not a perfect square";
?>
                                      

OUTPUT

Example 1
Enter the number: 25
The entered number 25 is a perfect square

Example 2
Enter the number: 15
The entered number 15 is not a perfect square