forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_exponentiation.py
48 lines (38 loc) · 1.02 KB
/
binary_exponentiation.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
45
46
47
48
"""Binary Exponentiation."""
# Author : Junth Basnet
# Time Complexity : O(logn)
def binary_exponentiation(a: int, n: int) -> int:
"""
Compute a number raised by some quantity
>>> binary_exponentiation(-1, 3)
-1
>>> binary_exponentiation(-1, 4)
1
>>> binary_exponentiation(2, 2)
4
>>> binary_exponentiation(3, 5)
243
>>> binary_exponentiation(10, 3)
1000
>>> binary_exponentiation(5e3, 1)
5000.0
>>> binary_exponentiation(-5e3, 1)
-5000.0
"""
if n == 0:
return 1
elif n % 2 == 1:
return binary_exponentiation(a, n - 1) * a
else:
b = binary_exponentiation(a, n // 2)
return b * b
if __name__ == "__main__":
import doctest
doctest.testmod()
try:
BASE = int(float(input("Enter Base : ").strip()))
POWER = int(input("Enter Power : ").strip())
except ValueError:
print("Invalid literal for integer")
RESULT = binary_exponentiation(BASE, POWER)
print(f"{BASE}^({POWER}) : {RESULT}")