Square Root using Python

Finding the square root of a number is asked in the coding interviews by FAANG companies many times. A square root is a number that produces the specified value when multiplied by itself. For example, 5×5 gives 25, so the square root of 25 is 5. So, if you want to learn how to find the square root of a number, this article is for you. In this article, I will take you through how to find the square root of a number using Python.

Square Root using Python

A square root is a number that gives a value when multiplied by itself. In coding interviews, you need to write a solution to find the square root of any number. While calculating the square root of a number, we get decimal values in the output most of the time. So while solving this question in the coding interviews, you will be allowed to return integer values as output.

Python has a built-in function to calculate the square root of a number. But in the coding interviews, you are not allowed to use any built-in function to return the square root of a number. So here’s how to calculate the square root of a number using the Python programming language:

def mySqrt(x):
    left = 1
    right = x
    mid = 0
    while (left <= right):
        mid = (left + right) // 2
        if mid * mid == x:
            return mid
        elif mid * mid > x:
            right = mid - 1
        else:
            left = mid + 1
            sqrt = mid
    return sqrt

print(mySqrt(25))
Output: 5

So this is how you can calculate the square root of any number using Python. You can find many more practice questions to improve your problem-solving skills using Python here.

Summary

Python has a built-in function to calculate the square root of a number. But in the coding interviews, you are not allowed to use any built-in function to return the square root of a number. I hope you liked this article on calculating the square root of a number using Python. Feel free to ask valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1297

Leave a Reply