From adbc4c4b38cd45f74769c1e87aee161f4f88f8a6 Mon Sep 17 00:00:00 2001 From: Walker Smith Date: Fri, 18 Jul 2025 21:30:55 -0400 Subject: [PATCH] solve problem --- leet-code/69-sqrt-x/README.md | 36 +++++++++++++++++++++++++++++++++++ leet-code/69-sqrt-x/index.js | 29 ++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 leet-code/69-sqrt-x/README.md create mode 100644 leet-code/69-sqrt-x/index.js diff --git a/leet-code/69-sqrt-x/README.md b/leet-code/69-sqrt-x/README.md new file mode 100644 index 0000000..8ef07a9 --- /dev/null +++ b/leet-code/69-sqrt-x/README.md @@ -0,0 +1,36 @@ +# 69-sqrt-x + +## Problem Statement + +Given a non-negative integer `x`, return the square root of `x` **rounded down** to the nearest integer. +The returned integer should be non-negative as well. + +**Do not use** any built-in exponent function or operator. +For example, do not use `pow(x, 0.5)` in C++ or `x ** 0.5` in Python. + +### Example 1: + +**Input:** +`x = 4` + +**Output:** +`2` + +**Explanation:** +The square root of 4 is 2, so we return 2. + +### Example 2: + +**Input:** +`x = 8` + +**Output:** +`2` + +**Explanation:** +The square root of 8 is approximately 2.82842... +Rounding down gives 2. + +### Constraints: + +- `0 <= x <= 2^31 - 1` diff --git a/leet-code/69-sqrt-x/index.js b/leet-code/69-sqrt-x/index.js new file mode 100644 index 0000000..bd93344 --- /dev/null +++ b/leet-code/69-sqrt-x/index.js @@ -0,0 +1,29 @@ +function initialGuess(x) { + const log2S = Math.log2(x); + const exponent = Math.floor(log2S / 2); + return Math.pow(2, exponent); +} + +/** + * Approximating Square Roots with Newton's Method + * f(x)=x^2−S + * x_n+1 = 1/2 * (x_n + S / x_n) + * + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + // short circuit on edge case + if (x === 0) return x + // speed up convergence with a reasonable guess + x0 = initialGuess(x) + // store the next tabulated value + let xn = x0; + // 32bit signed ints only need about 6 iterations to converge + for (var i = 0; i < 6; i++) { + // apply newtons method to find the root of the function + xn = (xn + (x/xn))/2 + } + // floor the approximation + return Math.floor(xn) +}; \ No newline at end of file