Square root by Newton’s method
Medium TimeO(log n) SpaceO(1)
Given a number n, approximate its square root without calling Math.sqrt. The answer is an approximation rather than the root itself: it is accepted as soon as its square is within 0.0001 of n, so even a perfect square comes back a little off. n is never negative, and the square root of 0 is 0.
Examples
Example 1
- Input
- n = 2
- Output
- Its square is
1.41421568627450972.0000060…, inside the0.0001allowed.
Example 2
- Input
- n = 16
- Output
- Not 4: its square is
4.00000063669293916.0000051…, which is already close enough.
The Code
function newtonSqrt(n) {
if (n === 0) return 0;
let guess = n;
let steps = 0;
while (Math.abs(guess * guess - n) > 0.0001 && steps < 50) {
guess = (guess + n / guess) / 2;
steps++;
}
return guess;
}
newtonSqrt(2);Done
More like this
All math & numbers examples (8) →- Prime check Only test odd divisors, and only up to the square root.
- Prime sieve Cross out every multiple; whatever survives is prime.
- Happy number Sum the squared digits until you reach 1 — or start repeating.
- Roman → integer Subtract when a smaller symbol sits before a bigger one.
- Integer → Roman Greedily take the largest symbol that still fits.
- Collatz Halve it if even, triple-plus-one if odd — always reaches 1.