29 lines
586 B
Python

# Sqrt(x)
# Do not use build in operator
class Solution:
def mySqrt(self, c: int) -> int:
# Use Newton's method, return the smaller root
# fx = x ** 2 - c
# Xn-1 = 0.5 * (Xn + c / Xn)
if c == 0:
return 0
if c == 1:
return 1
x = c / 2
while True:
next_x = (x + c / x) / 2
if x - next_x > -1 and x - next_x <= 0:
break
x = next_x
return int(x)
if __name__ == "__main__":
print(Solution().mySqrt(13))
print(Solution().mySqrt(16))