- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements