Find Square Root Of Given Number - Python
Last Updated :
24 Feb, 2025
Given an integer X, find its square root. If X is not a perfect square, then return floor(√x). For example, if X = 11, the output should be 3, as it is the largest integer less than or equal to the square root of 11.
Using built-in functions
We can also find the floor of the square root using Python’s built-in exponentiation operator (**) and then integer conversion.
Python
def countSquares(x):
sqrt = x**0.5
result = int(sqrt)
return result
# driver code
x = 9
print(countSquares(x))
Explanation: x**0.5 calculates the square root of x, and int(sqrt) converts it to the largest integer less than or equal to the sqrt.
Using numpy + math library
The same result can be obtained by using the numpy.sqrt() function to compute the square root and then applying math.floor() to round it down to the nearest integer.
Python
import numpy as np
import math
sr = np.sqrt(10)
# Apply floor function
print(math.floor(sr))
Explanation: np.sqrt(10) function computes the square root of 10, resulting in approximately 3.162. The math.floor(sr) function then rounds it down to 3
Note: numpy.sqrt() returns a Numpy array if the input is an array, and a single value if the input is a single number.
Using Binary search
We can also use binary search to do the same task, making it more efficient than brute-force approaches. Instead of iterating through all numbers, it repeatedly halves the search space, significantly reducing the number of calculations.
Python
def floorSqrt(x):
# Base case
if (x == 0 or x == 1):
return x
# Do Binary Search for floor(sqrt(x))
start = 1
end = x//2
while (start <= end):
mid = (start + end) // 2
# If x is a perfect square
if (mid*mid == x):
return mid
# Since we need floor, we update answer when
# mid*mid is smaller than x, and move closer to sqrt(x)
if (mid * mid < x):
start = mid + 1
ans = mid
else:
# If mid*mid is greater than x
end = mid-1
return ans
# driver code
x = 11
print(floorSqrt(x))
Explanation: If x is 0 or 1, it returns x. Otherwise, it initializes start = 1 and end = x // 2 and performs binary search. It calculates mid and checks if mid² == x. If not, it adjusts start or end accordingly, storing the closest possible square root (ans).
Using Brute force
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.
Python
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
x = 18
print(floorSqrt(x))
Explanation: Increment i while i * i is ≤ x. Once i * i exceeds x, it returns i - 1 as the largest integer whose square is ≤ x.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read