Solve 69. Sqrt(x)
This commit is contained in:
parent
72cc7fb185
commit
6f468c4c98
12
python/69_sqrtx.py
Normal file
12
python/69_sqrtx.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
class Solution:
|
||||||
|
def mySqrt(self, x: int) -> int:
|
||||||
|
# Use Newton-Raphson iteration
|
||||||
|
# y**2 - x = 0 = f(y)
|
||||||
|
# f'(y) = 2y
|
||||||
|
# y = y - (y**2 - x)/(2y)
|
||||||
|
y = 1
|
||||||
|
close_enough = False
|
||||||
|
while not close_enough:
|
||||||
|
y -= (y*y-x)/(2*y)
|
||||||
|
close_enough = y*y - x <= 0.1 and (y+1)*(y+1) > x
|
||||||
|
return floor(y)
|
Loading…
Reference in New Issue
Block a user