[LeetCode][50. Pow(x, n)] Fast Power Algorithm: Binary Exponentiation
By Long Luo
This article is the solution Fast Power Algorithm: Binary Exponentiation of Problem 50. Pow(x, n) .
We know how to find \(2.0\) raised to the power \(10\). The easiest way is to multiply \(10\) times \(2.0\) by loop, but what if we have to find \(2.0\) raised to the power very large number such as \(10000\) or more?
We will discuss how to find the solution of such problems by using an fast, efficient algorithm.
Brute Force
We multiply \(a\) to itself \(b\) times. That is, \(a^b = \underbrace{a \times a \dots \times a}_b\).
A simple java implementation of that would be:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public static double myPow(double x, int n) {
if (n == 0 || x == 1) {
return 1;
} else if (x == 0) {
return 0;
}
double ans = x;
boolean isNegative = false;
long nLong = n;
if (nLong < 0) {
nLong = -nLong;
isNegative = true;
}
for (int i = 1; i < nLong; i++) {
ans = ans * x;
}
if (isNegative) {
ans = 1 / ans;
}
return ans;
}
Analysis
- Time Complexity: \(O(n)\)
- Space Complexity: \(O(1)\)