2019-07-10 20:09:24 +00:00
|
|
|
"""Binary Exponentiation."""
|
|
|
|
|
|
|
|
# Author : Junth Basnet
|
|
|
|
# Time Complexity : O(logn)
|
|
|
|
|
2019-05-10 11:03:05 +00:00
|
|
|
|
|
|
|
def binary_exponentiation(a, n):
|
2019-10-05 05:14:13 +00:00
|
|
|
if n == 0:
|
2019-05-10 11:03:05 +00:00
|
|
|
return 1
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
elif n % 2 == 1:
|
2019-05-10 11:03:05 +00:00
|
|
|
return binary_exponentiation(a, n - 1) * a
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-05-10 11:03:05 +00:00
|
|
|
else:
|
|
|
|
b = binary_exponentiation(a, n / 2)
|
|
|
|
return b * b
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-07-21 06:16:28 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
try:
|
|
|
|
BASE = int(input("Enter Base : ").strip())
|
|
|
|
POWER = int(input("Enter Power : ").strip())
|
|
|
|
except ValueError:
|
|
|
|
print("Invalid literal for integer")
|
|
|
|
|
|
|
|
RESULT = binary_exponentiation(BASE, POWER)
|
2019-12-07 05:39:59 +00:00
|
|
|
print(f"{BASE}^({POWER}) : {RESULT}")
|