Python Program to Find the Square Root

To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number.

Follow the steps below to implement the above idea

  1. Create a variable (counter) i and take care of some base cases, (i.e when the given number is 0 or 1).
  2. Run a loop until i*i <= n, where n is the given number. Increment i by 1.
  3. The floor of the square root of the number is i – 1

Below is the implementation of the above approach:

Python3




# Python3 program to find floor(sqrt(x)
 
# Returns floor of square root of x
 
 
def floorSqrt(x):
 
    # Base cases
    if (x == 0 or x == 1):
        return x
 
    # Starting from 1, try all numbers until
    # i*i is greater than or equal to x.
    i = 1
    result = 1
    while (result <= x):
 
        i += 1
        result = i * i
 
    return i - 1
 
 
# Driver Code
x = 11
print(floorSqrt(x))


Output

3

Complexity Analysis: 

  • Time Complexity: O(√X). Only one traversal of the solution is needed, so the time complexity is O(√X).
  • Auxiliary Space: O(1).

Python Program To Find Square Root Of Given Number

Given an integer X, find its square root. If X is not a perfect square, then return floor(√x).

Examples:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.

Input: x = 11
Output: 3
Explanation:  The square root of 11 lies in between 3 and 4 so floor of the square root is 3.

Similar Reads

Python Program to Find the Square Root

To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number....

Square root an integer using Binary search

...

Square root an integer using built-in functions

The idea is to find the largest integer i whose square is less than or equal to the given number. The values of i * i is monotonically increasing, so the problem can be solved using binary search....