Guess Nearest Square Root in Python

Finding the square root of a number without using built-in functions is a classic programming problem. We need to find the largest integer r such that r * r ? n, effectively rounding down to the nearest integer.

So, if the input is 1025, then the output will be 32 because 32² = 1024 ? 1025, but 33² = 1089 > 1025.

Algorithm Steps

We'll use binary search to efficiently find the square root ?

  • If n ? 1, return n (base case)
  • Set start = 1, end = n
  • While start < end:
    • Calculate mid = (start + end) // 2
    • If mid² ? n, search in the right half: start = mid + 1
    • Otherwise, search in the left half: end = mid
  • Return start - 1 (the largest valid square root)

Implementation

class Solution:
    def solve(self, n):
        if n <= 1:
            return n
        
        start, end = 1, n
        while start < end:
            mid = (start + end) // 2
            if mid * mid <= n:
                start = mid + 1
            else:
                end = mid
        return start - 1

# Test the solution
ob = Solution()
print(f"Square root of 1025: {ob.solve(1025)}")
print(f"Square root of 16: {ob.solve(16)}")
print(f"Square root of 15: {ob.solve(15)}")
Square root of 1025: 32
Square root of 16: 4
Square root of 15: 3

How It Works

The algorithm uses binary search with the following logic ?

def demonstrate_steps(n):
    print(f"Finding square root of {n}")
    start, end = 1, n
    step = 1
    
    while start < end:
        mid = (start + end) // 2
        square = mid * mid
        print(f"Step {step}: start={start}, end={end}, mid={mid}, mid²={square}")
        
        if square <= n:
            start = mid + 1
            print(f"  {square} ? {n}, so search right half")
        else:
            end = mid
            print(f"  {square} > {n}, so search left half")
        step += 1
    
    result = start - 1
    print(f"Final result: {result}")
    return result

demonstrate_steps(25)
Finding square root of 25
Step 1: start=1, end=25, mid=13, mid²=169
  169 > 25, so search left half
Step 2: start=1, end=13, mid=7, mid²=49
  49 > 25, so search left half
Step 3: start=1, end=7, mid=4, mid²=16
  16 ? 25, so search right half
Step 4: start=5, end=7, mid=6, mid²=36
  36 > 25, so search left half
Step 5: start=5, end=6, mid=5, mid²=25
  25 ? 25, so search right half
Final result: 5

Alternative Approach: Newton's Method

def newton_square_root(n):
    if n < 2:
        return n
    
    # Start with an initial guess
    x = n
    while True:
        # Newton's iteration: x_new = (x + n/x) / 2
        x_new = (x + n // x) // 2
        if x_new >= x:
            return x
        x = x_new

# Test Newton's method
print(f"Newton method for 1025: {newton_square_root(1025)}")
print(f"Newton method for 16: {newton_square_root(16)}")
Newton method for 1025: 32
Newton method for 16: 4

Comparison

Method Time Complexity Space Complexity Best For
Binary Search O(log n) O(1) Easy to understand
Newton's Method O(log log n) O(1) Faster convergence

Conclusion

Binary search provides an efficient O(log n) solution to find integer square roots without built-in functions. Newton's method offers even faster convergence but is slightly more complex to implement.

Updated on: 2026-03-25T10:23:48+05:30

649 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements