Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions leet-code/69-sqrt-x/README.md
Original file line number Diff line number Diff line change
@@ -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`
29 changes: 29 additions & 0 deletions leet-code/69-sqrt-x/index.js
Original file line number Diff line number Diff line change
@@ -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)
};