Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sqrt(x) in Python
Finding the square root of a number without using library functions is a common programming challenge. We need to implement our own function that returns the integer part of the square root, truncating any decimal digits.
For example, if x = 4, the result is 2. If x = 8, the result is also 2 (since ?8 = 2.828... but we take only the integer part).
Algorithm Overview
We use binary search to find the square root efficiently ?
- Initialize low = 1, high = x + 1, and answer = 0
- While high > low:
- Calculate mid = (high + low) // 2
- If mid * mid ? x, then low = mid + 1 and answer = mid
- Otherwise, high = mid
- Return answer
Implementation
class Solution:
def mySqrt(self, x):
"""
Find integer square root using binary search
:param x: non-negative integer
:return: integer part of square root
"""
if x == 0:
return 0
low = 1
high = x + 1
answer = 0
while high > low:
mid = (high + low) // 2
if mid * mid <= x:
low = mid + 1
answer = mid
else:
high = mid
return answer
# Test the implementation
solution = Solution()
print("?4 =", solution.mySqrt(4))
print("?16 =", solution.mySqrt(16))
print("?7 =", solution.mySqrt(7))
print("?15 =", solution.mySqrt(15))
print("?25 =", solution.mySqrt(25))
?4 = 2 ?16 = 4 ?7 = 2 ?15 = 3 ?25 = 5
How It Works
The binary search approach works by narrowing down the search space:
- Search Range: Between 1 and x+1
- Condition: If mid² ? x, the answer could be mid or larger
- Update: Move the search boundary based on the comparison
- Result: The largest integer whose square is ? x
Alternative Implementation
Here's a simpler version without the class structure ?
def sqrt_integer(x):
"""Find integer square root using binary search"""
if x == 0:
return 0
low, high = 1, x + 1
result = 0
while low < high:
mid = (low + high) // 2
if mid * mid <= x:
result = mid
low = mid + 1
else:
high = mid
return result
# Test cases
test_values = [0, 1, 4, 8, 15, 16, 25, 100]
for val in test_values:
print(f"?{val} = {sqrt_integer(val)}")
?0 = 0 ?1 = 1 ?4 = 2 ?8 = 2 ?15 = 3 ?16 = 4 ?25 = 5 ?100 = 10
Time and Space Complexity
- Time Complexity: O(log x) - binary search reduces search space by half each iteration
- Space Complexity: O(1) - only using a few variables
Conclusion
Binary search provides an efficient way to find integer square roots without library functions. The algorithm runs in O(log x) time and handles edge cases like x = 0 correctly.
