There was an error while loading. Please reload this page.
1 parent e278aed commit 6a2ca68Copy full SHA for 6a2ca68
1 file changed
maths/fermat_little_theorem.py
@@ -5,15 +5,25 @@
5
# Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem
6
7
8
-def binary_exponentiation(a: int, n: float, mod: int) -> int:
+def binary_exponentiation(a: int, n: int, mod: int) -> int:
9
+ """
10
+ Calculate (a ** n) % mod using binary exponentiation, which runs in O(log n) time.
11
+
12
+ >>> binary_exponentiation(2, 10, 17)
13
+ 4
14
+ >>> binary_exponentiation(3, 0, 5)
15
+ 1
16
+ >>> binary_exponentiation(5, 3, 13)
17
+ 8
18
19
if n == 0:
20
return 1
21
22
elif n % 2 == 1:
23
return (binary_exponentiation(a, n - 1, mod) * a) % mod
24
25
else:
- b = binary_exponentiation(a, n / 2, mod)
26
+ b = binary_exponentiation(a, n // 2, mod)
27
return (b * b) % mod
28
29
0 commit comments