0
0
PhpProgramBeginner · 2 min read

PHP Program to Find Square Root of a Number

You can find the square root of a number in PHP using the sqrt() function like this: $result = sqrt($number);.
📋

Examples

Input16
Output4
Input25
Output5
Input0
Output0
🧠

How to Think About It

To find the square root of a number, think of it as finding a value that when multiplied by itself gives the original number. PHP has a built-in function sqrt() that does this calculation easily.
📐

Algorithm

1
Get the input number.
2
Use the built-in function to calculate the square root.
3
Return or print the result.
💻

Code

php
<?php
$number = 16;
$result = sqrt($number);
echo "Square root of $number is $result";
?>
Output
Square root of 16 is 4
🔍

Dry Run

Let's trace the example where the input number is 16 through the code.

1

Assign input

$number = 16

2

Calculate square root

$result = sqrt(16) which equals 4

3

Print result

Output: Square root of 16 is 4

StepVariableValue
1$number16
2$result4
3OutputSquare root of 16 is 4
💡

Why This Works

Step 1: Input number stored

The number you want the square root of is stored in a variable using $number = 16;.

Step 2: Calculate square root

The sqrt() function calculates the square root of the number and stores it in $result.

Step 3: Display output

The result is printed using echo to show the square root clearly.

🔄

Alternative Approaches

Using exponentiation operator
php
<?php
$number = 16;
$result = $number ** 0.5;
echo "Square root of $number is $result";
?>
This uses the power operator to find the square root by raising the number to 0.5 power. It is simple but less explicit than sqrt().
Using pow() function
php
<?php
$number = 16;
$result = pow($number, 0.5);
echo "Square root of $number is $result";
?>
The pow() function raises the number to the 0.5 power to get the square root. It is flexible for other powers but less direct than sqrt().

Complexity: O(1) time, O(1) space

Time Complexity

Calculating square root with sqrt() or exponentiation is a constant time operation because it uses built-in math functions.

Space Complexity

Only a few variables are used, so space complexity is constant.

Which Approach is Fastest?

Using sqrt() is the fastest and most readable. Exponentiation and pow() are slightly less direct but perform similarly.

ApproachTimeSpaceBest For
sqrt() functionO(1)O(1)Clear and direct square root calculation
Exponentiation operatorO(1)O(1)Simple math expression, flexible for powers
pow() functionO(1)O(1)General power calculations, less direct for square root
💡
Use sqrt() for clear and direct square root calculation in PHP.
⚠️
Trying to calculate square root by multiplying or dividing instead of using sqrt() or exponentiation.