-
Notifications
You must be signed in to change notification settings - Fork 257
/
fast-power.cpp
48 lines (46 loc) · 975 Bytes
/
fast-power.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Time: O(logn)
// Space: O(1)
// Iterative solution.
class Solution {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastPower(int a, int b, int n) {
long long result = 1;
long long x = a % b;
while (n > 0) {
if (n & 1) {
result = result * x % b;
}
n >>= 1;
x = x * x % b;
}
return result % b;
}
};
// Time: O(logn)
// Space: O(logn)
// Recursive solution.
class Solution2 {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastPower(int a, int b, int n) {
if (n == 0) {
return 1 % b;
}
if (n == 1) {
return a % b;
}
long long tmp = fastPower(a, b, n / 2);
if (n % 2 == 0) {
return (tmp * tmp) % b;
} else {
return ((tmp * tmp) % b * a) % b;
}
}
};