Pow(x, n)
Implementpow(x,n), which calculates x_raised to the power_n(xn).
Example 1:
Example 2:
Example 3:
Solution
Brute force solution.
Intuition
Assuming we have got the result ofxnxn, how can we getx2∗nx2∗n? Obviously we do not need to multiplyx
for anothern
times. Using the formula(xn)=x2∗n(xn)2=x2∗n, we can getx2∗nx2∗nat the cost of only one computation. Using this optimization, we can reduce the time complexity of our algorithm.
Algorithm
Assume we have got the result ofxn/2xn/2, and now we want to get the result ofxnxn. LetA
be result ofxn/2xn/2, we can talk aboutxnxnbased on the parity ofn
respectively. Ifn
is even, we can use the formula(xn)=x2∗n(xn)2=x2∗nto getxn=A∗Axn=A∗A. Ifn
is odd, thenA∗A=xn−1A∗A=xn−1. Intuitively, We need to multiply anotherxxto the result, soxn=A∗A∗xxn=A∗A∗x. This approach can be easily implemented using recursion. We call this method "Fast Power", because we only need at mostO(log(n))O(log(n))computations to getxnxn.
Iterative version of previous algorithm.
Last updated
Was this helpful?