[Leetcode][69. Sqrt(x)] 4 Approaches for Finding the Square Root of A Number: Brute Force, Exponent, Binary Search and the Newton Iteration Method
By Long Luo
This article is the solution 4 Approaches: Brute Force, Exponent, Binary Search and the Newton’s Iteration Method of Problem 69. Sqrt(x) .
Here shows 4 approaches for finding the square root of a number: Brute Force, Exponent, Binary Search and the Newton’s Iteration Method.
Given an integer \(N\) and a tolerance level \(L\), the task is to find the square root of that number.
Brute Force
The Brute Force way is very easy, just enumerate a value from \(0\) to \(x\), check the product \(i^2\) and target, return the answer.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static int mySqrt(int x) {
if (x == 0 || x == 1) {
return x;
}
for (int i = 0; i < x; i++) {
long sum = i * i;
long bigger = (long) (i + 1) * (i + 1);
if (sum == x) {
return i;
} else if (sum < x && bigger > x) {
return i;
}
}
return 0;
}
Analysis
- Time Complexity: \(O(n)\)
- Space Complexity: \(O(1)\)
Exponent
Noted that:
\[ \sqrt{x} = x^{1/2} = (e ^ {\ln x})^{1/2} = e^{\frac{1}{2} \ln x} \]
So we can use the exponent \(\exp\) and logarithm \(\ln\) to calculate the square root of the number \(\sqrt{x}\).
It’s really a fast and simple way!
Note: Since the computer can’t store the exact value of the float number, and the parameters and return values of the exponential function and logarithmic function are float numbers, so the result may be wrong.
For example, when \(x = 2147395600\), the result of \(e^{\frac{1}{2} \ln x}\) is \(10^{-11}\) from the correct value of \(46340\) , so when taking the integer part of the result, you will get the wrong result of \(46339\) .
So after getting the integer part \(\textit{ans}\) of the result, we should find out which of \(\textit{ans}\) and \(\textit{ans} + 1\) is the real answer.1
2
3
4
5
6
7
8// Exp O(1) O(1)
public static int mySqrt_exp(int x) {
if (x == 0) {
return 0;
}
int ans = (int) Math.exp(0.5 * Math.log(x));
return (long) (ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
}
Analysis
- Time Complexity: \(O(1)\)
- Space Complexity: \(O(1)\).