Sqrt(x) (newtons method) - Math - Easy - LeetCode
💻 coding

Sqrt(x) (newtons method) - Math - Easy - LeetCode

2 min read 333 words
2 min read
ShareWhatsAppPost on X
  • 1The task is to implement a function that computes the integer square root of a non-negative integer x.
  • 2The Newton's method is used to iteratively approximate the square root, ensuring efficient convergence.
  • 3The time complexity of the algorithm is O(log n) and the space complexity is O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to implement a function that computes the integer square root of a non-negative integer x."

Sqrt(x) (newtons method) - Math - Easy - LeetCode

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4 Output: 2 Example 2:

Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

public class Solution {
 public int MySqrt(int x) {
 long num = x;
 while (num*num > x)
 num = (num + x/num) / 2;
 return (int) num;
 }
}

Time Complexity: O(logn)

Space Complexity: O(1)

Given y = f(x), find the root x such that f(x) = 0, geometrically speaking, find the intersection of the function y and the x-axis.

For a roughly estimated root x0, it's coordinate on the function is P(x0, f(x0)). We can find P's tangent line L whose slope is m, such that the intersection of the L and the x-axis, say S(x1, 0), it's function value f(x1) is closer to the real root of y = f(x), comparing to the f(x0).

Set m = f'(x0), where f' denotes the differential on x0 ... (1) The slope m is defined by PS: m = (f(x0) - 0) / (x0 - x1) ... (2) Combine (1) (2), f'(x0) = f(x0) / (x0 - x1) => x0 - x1 = f(x0) / f'(x0) => x1 = x0 - f(x0) / f'(x0)

x(n+1) = x(n) - f(x(n)) / f'(x(n)) By applying Newton's method to the root problem, finding the r such that r^2 equals to the input x is the same as finding the root of f(r) where

f(r) = r^2 - x = 0 => r(n+1) = r(n) - f(r(n)) / f'(r(n)) => r(n+1) = r(n) - (r(n)^2 - x) / 2 * r(n) => r(n+1) = r(n) - r(n) / 2 + x / 2 * r(n) => r(n+1) = (r(n) + x / r(n)) / 2

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 2 min read · 333 words

Part of AskGif Blog · coding

You might also like