Given a positive number, return the square root of it. If the number is not a perfect square, return the floor of its square root.

For example,

Input:  x = 12
Output: 3
 
Input:  x = 16
Output: 4

Practice this problem

A naive solution is to consider all positive numbers starting from 1 and find the first number i for which i2 is greater than the given number x. Then i-1 would be the floor of the square root of x.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
sqrt(0) = 0
sqrt(1) = 1
sqrt(2) = 1
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(6) = 2
sqrt(7) = 2
sqrt(8) = 2
sqrt(9) = 3
sqrt(10) = 3
sqrt(11) = 3
sqrt(12) = 3
sqrt(13) = 3
sqrt(14) = 3
sqrt(15) = 3
sqrt(16) = 4

The time complexity of the above solution is O(√x) and doesn’t require any extra space. We can improve the time complexity to O(log(x)) with the help of the binary search algorithm. The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
sqrt(0) = 0
sqrt(1) = 1
sqrt(2) = 1
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(6) = 2
sqrt(7) = 2
sqrt(8) = 2
sqrt(9) = 3
sqrt(10) = 3
sqrt(11) = 3
sqrt(12) = 3
sqrt(13) = 3
sqrt(14) = 3
sqrt(15) = 3
sqrt(16) = 4