2023-10-02 14:30:34 +00:00
|
|
|
def bin_exp_mod(a: int, n: int, b: int) -> int:
|
2019-12-24 06:23:15 +00:00
|
|
|
"""
|
|
|
|
>>> bin_exp_mod(3, 4, 5)
|
|
|
|
1
|
|
|
|
>>> bin_exp_mod(7, 13, 10)
|
|
|
|
7
|
|
|
|
"""
|
|
|
|
# mod b
|
2023-03-01 16:23:33 +00:00
|
|
|
assert b != 0, "This cannot accept modulo that is == 0"
|
2019-12-24 06:23:15 +00:00
|
|
|
if n == 0:
|
|
|
|
return 1
|
|
|
|
|
|
|
|
if n % 2 == 1:
|
|
|
|
return (bin_exp_mod(a, n - 1, b) * a) % b
|
|
|
|
|
2023-10-02 14:30:34 +00:00
|
|
|
r = bin_exp_mod(a, n // 2, b)
|
2019-12-24 06:23:15 +00:00
|
|
|
return (r * r) % b
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
try:
|
|
|
|
BASE = int(input("Enter Base : ").strip())
|
|
|
|
POWER = int(input("Enter Power : ").strip())
|
|
|
|
MODULO = int(input("Enter Modulo : ").strip())
|
|
|
|
except ValueError:
|
|
|
|
print("Invalid literal for integer")
|
|
|
|
|
|
|
|
print(bin_exp_mod(BASE, POWER, MODULO))
|