forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
power.py
45 lines (38 loc) · 902 Bytes
/
power.py
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
def power(a: int, n: int, r: int = None):
"""
Iterative version of binary exponentiation
Calculate a ^ n
if r is specified, return the result modulo r
Time Complexity : O(log(n))
Space Complexity : O(1)
"""
ans = 1
while n:
if n & 1:
ans = ans * a
a = a * a
if r:
ans %= r
a %= r
n >>= 1
return ans
def power_recur(a: int, n: int, r: int = None):
"""
Recursive version of binary exponentiation
Calculate a ^ n
if r is specified, return the result modulo r
Time Complexity : O(log(n))
Space Complexity : O(log(n))
"""
if n == 0:
ans = 1
elif n == 1:
ans = a
else:
ans = power_recur(a, n // 2, r)
ans = ans * ans
if n % 2:
ans = ans * a
if r:
ans %= r
return ans