PHP Check if Given Number is Perfect Square
Given a number, the task is to check the given number is a perfect square in PHP. A perfect square is an integer that is the square of another integer. For example, 16 is a perfect square because it is the square of 4.
Examples:
Input: num = 16
Output: Perfect Square
Input: 18
Output: Not a Perfect Square
These are the following approaches:
Table of Content
- Using the sqrt() Function
- Using a Loop
Approach 1: Using the sqrt() Function
The basic method to check if a number is a perfect square is by using the sqrt() function, which returns the square root of a number. If the square root is an integer, then the number is a perfect square.
Example: The isPerfectSquare() function takes an integer $number as an argument and calculates its square root using the sqrt() function. It then checks if the square root is equal to the floor value of the square root (floor($sqrt)). If they are equal, the number is a perfect square.
<?php
function isPerfectSquare($number) {
$sqrt = sqrt($number);
return $sqrt == floor($sqrt);
}
$n = 16;
if (isPerfectSquare($n)) {
echo "$n is a perfect square.";
} else {
echo "$n is not a perfect square.";
}
?>
Output
16 is a perfect square.
Approach 2: Using a Loop
Another method to check if a number is a perfect square is by using a loop to find a number whose square is equal to the given number.
Example: The isPerfectSquare() function iterates through numbers starting from 1 and checks if the square of the current number ($i * $i) is equal to the given number. If it finds such a number, the function returns true, indicating that the number is a perfect square. Otherwise, it returns false.
<?php
function isPerfectSquare($number) {
for ($i = 1; $i * $i <= $number; $i++) {
if ($i * $i == $number) {
return true;
}
}
return false;
}
$n = 16;
if (isPerfectSquare($n)) {
echo "$n is a perfect square.";
} else {
echo "$n is not a perfect square.";
}
?>
Output
16 is a perfect square.
Contact Us