Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Working with Negative Numbers in Python
Next article icon

Find Square Root Of Given Number - Python

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)) 

Output
3 

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.

Table of Content

  • Using Brute force
  • Using Binary search
  • Using numpy + math library

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)) 

Output
3 

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)) 

Output
3 

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)) 

Output
4 

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.


Next Article
Working with Negative Numbers in Python
author
kartik
Improve
Article Tags :
  • Divide and Conquer
  • Python
  • Python Programs
  • DSA
  • Microsoft
  • Amazon
  • Snapdeal
  • Accolite
  • Ola Cabs
  • Binary Search
Practice Tags :
  • Accolite
  • Amazon
  • Microsoft
  • Ola Cabs
  • Snapdeal
  • Binary Search
  • Divide and Conquer
  • python

Similar Reads

  • Sum the Digits of a Given Number - Python
    The task of summing the digits of a given number in Python involves extracting each digit and computing their total . For example, given the number 12345, the sum of its digits is 1 + 2 + 3 + 4 + 5 = 15. Using modulo (%)This method efficiently extracts each digit using the modulus (%) and integer di
    2 min read
  • Minimum of two numbers in Python
    In this article, we will explore various methods to find minimum of two numbers in Python. The simplest way to find minimum of two numbers in Python is by using built-in min() function. [GFGTABS] Python a = 7 b = 3 print(min(a, b)) [/GFGTABS]Output3 Explanation: min() function compares the two numbe
    2 min read
  • Python program to calculate square of a given number
    The task of calculating the square of a number in Python involves determining the result of multiplying a number by itself. For example, given the number 4, its square is 16 because 4 × 4 = 16. Using ** operatorexponentiation operator (**) is the most direct and optimized way to compute powers. Sinc
    1 min read
  • Working with Negative Numbers in Python
    Negative numbers play a crucial role in various mathematical and programming scenarios. In Python, handling negative numbers is a fundamental skill for developers. In this article, we will explore some commonly used methods for working with negative numbers in Python, along with examples to illustra
    3 min read
  • Python Program to Find the Gcd of Two Numbers
    The task of finding the GCD (Greatest Common Divisor) of two numbers in Python involves determining the largest number that divides both input values without leaving a remainder. For example, if a = 60 and b = 48, the GCD is 12, as 12 is the largest number that divides both 60 and 48 evenly. Using e
    2 min read
  • Python program to find smallest number in a list
    In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function. Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value. [GFGTABS]
    3 min read
  • Number System in Python
    The arithmetic value that is used for representing the quantity and used in making calculations is defined as NUMBERS. The writing system for denoting numbers logically using digits or symbols is defined as a Number system. Number System is a system that defines numbers in different ways to represen
    6 min read
  • Python Program to Find Cube of a Number
    We are given a number and our task is to find the cube of this number in Python. The cube of a number is calculated by multiplying the number by itself twice. For example, if the input is 3, then the output will be 3 * 3 * 3 = 27. In this article, we will learn different ways to find the cube of a n
    2 min read
  • Python program to find the smallest number in a file
    Given a text file, write a Python program to find the smallest number in the given text file. Examples: Input: gfg.txtOutput: 9Explanation: Contents of gfg.txt: I live at 624 Hyderabad.My mobile number is 52367. My favourite number is 9.Numbers present in the text file are 9,624,52367Minimum number
    3 min read
  • How to Find Index of a Substring in Python
    In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Let’s look at some simple ways to find the index of a substring in a string. Using find() methodTh
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences