Cover image for Interview Classic 150 Problem P50 Pow(x, n)

Interview Classic 150 Problem P50 Pow(x, n)


Timeline

Timeline

2025-11-26

init

Math

Problem:

If we directly loopntimes, the time isO(n), it will time out. Use fast exponentiation:

Fast exponentiation is based on a fact:

  • If n is even:

    xn=(x2)n/2x^n = (x^2)^{n/2}

  • If n is odd:

    xn=xxn1x^n = x \cdot x^{n-1}

Each time n is halved, so the time complexity isO(log n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class Solution {
public:
double myPow(double x, int n)
{
// Fast Exponentiation
long pow = (long)n;
if (pow < 0) {
x = 1 / x;
pow = -pow;
}

double res = 1;
while (pow > 0) {
if ((pow & 0x1) == 0) {
x = x * x;
pow = pow / 2;
} else {
res *= x;
pow = pow - 1;
}
}
return res;
}
};