From 6f468c4c98bf72f386944bb3a09dbed45e9f0408 Mon Sep 17 00:00:00 2001 From: ktkovachev <143198904+ktkovachev@users.noreply.github.com> Date: Mon, 8 Apr 2024 16:56:16 +0100 Subject: [PATCH] Solve 69. Sqrt(x) --- python/69_sqrtx.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 python/69_sqrtx.py diff --git a/python/69_sqrtx.py b/python/69_sqrtx.py new file mode 100644 index 0000000..6db86e1 --- /dev/null +++ b/python/69_sqrtx.py @@ -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)