
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Guess Nearest Square Root in Python
Suppose we have a non-negative number n, we have to find a number r such that r * r = n and we have to round down to the nearest integer. We have to solve this problem without using the builtin square-root function.
So, if the input is like 1025, then the output will be 32.
To solve this, we will follow these steps −
- if n <= 1, then
- return n
- start := 1, end := n
- while start < end, do
- mid := start + end/2
- if mid * mid <= n, then
- start := mid + 1
- otherwise,
- end := mid
- return start - 1
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): if n <= 1: return n start, end = 1, n while start < end: mid = start + end >> 1 if mid * mid <= n: start = mid + 1 else: end = mid return start - 1 ob = Solution() print(ob.solve(1025))
Input
1025
Output
32
- Related Articles
- Square and Square root in Arduino
- How to calculate square root of a number in Python?
- How to find Square root of complex numbers in Python?
- Compute the square root of input with emath in Python
- What is square root and cube root?
- How to perform square root without using math module in Python?
- Compute the square root of negative input with emath in Python
- Compute the square root of complex inputs with scimath in Python
- Fast inverse square root in C++
- 8086 program to find the square root of a perfect square root number
- What Is the Square Root?
- You are told that 1,331 is a perfect cube. Can you guess without factorisation is its cube root? Similarly, guess the cube roots of 4913,12167,32768
- Find the square root of 2025.
- What is mean by square root ?
- Find the square root of 3.5.

Advertisements