forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower.py
More file actions
72 lines (58 loc) · 1.46 KB
/
power.py
File metadata and controls
72 lines (58 loc) · 1.46 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Binary Exponentiation
Compute a^n efficiently using binary exponentiation (exponentiation by
squaring), with optional modular arithmetic.
Reference: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
Complexity:
Time: O(log n)
Space: O(1) iterative, O(log n) recursive
"""
from __future__ import annotations
def power(a: int, n: int, mod: int | None = None) -> int:
"""Compute a^n iteratively using binary exponentiation.
Args:
a: The base.
n: The exponent.
mod: Optional modulus for modular exponentiation.
Returns:
a^n, or a^n % mod if mod is specified.
Examples:
>>> power(2, 3)
8
>>> power(10, 3, 5)
0
"""
ans = 1
while n:
if n & 1:
ans = ans * a
a = a * a
if mod:
ans %= mod
a %= mod
n >>= 1
return ans
def power_recur(a: int, n: int, mod: int | None = None) -> int:
"""Compute a^n recursively using binary exponentiation.
Args:
a: The base.
n: The exponent.
mod: Optional modulus for modular exponentiation.
Returns:
a^n, or a^n % mod if mod is specified.
Examples:
>>> power_recur(2, 3)
8
"""
if n == 0:
ans = 1
elif n == 1:
ans = a
else:
ans = power_recur(a, n // 2, mod)
ans = ans * ans
if n % 2:
ans = ans * a
if mod:
ans %= mod
return ans