forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodular_exponential.py
More file actions
46 lines (34 loc) · 1 KB
/
modular_exponential.py
File metadata and controls
46 lines (34 loc) · 1 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
"""
Modular Exponentiation
Compute (base ^ exponent) % mod efficiently using binary exponentiation
(repeated squaring).
Reference: https://en.wikipedia.org/wiki/Modular_exponentiation
Complexity:
Time: O(log exponent)
Space: O(1)
"""
from __future__ import annotations
def modular_exponential(base: int, exponent: int, mod: int) -> int:
"""Compute (base ^ exponent) % mod using binary exponentiation.
Args:
base: The base value.
exponent: The exponent (must be non-negative).
mod: The modulus.
Returns:
The result of (base ^ exponent) % mod.
Raises:
ValueError: If exponent is negative.
Examples:
>>> modular_exponential(5, 117, 19)
1
"""
if exponent < 0:
raise ValueError("Exponent must be positive.")
base %= mod
result = 1
while exponent > 0:
if exponent & 1:
result = (result * base) % mod
exponent = exponent >> 1
base = (base * base) % mod
return result