Guess Nearest Square Root in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 23-Sep-2020 10:30:46
Advertisements