How to usethe sqrt() Function in PHP
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.
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
Contact Us