This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
ProgrammingChallenges/modular_exponentiation.py
2019-04-04 22:03:21 +02:00

30 lines
600 B
Python
Executable file

import math
import sys
def mod_exp(x, y, m):
k = x % m
results = {}
return exp_m(results, k, y, m)
def exp_m(results, k, y, m):
if y in results:
return results[y]
else:
if k == 1:
ret = 1
elif y == 0:
ret = 1
elif y == 1:
ret = k
else:
h = y // 2
ret = (exp_m(results, k, h, m) % m * exp_m(results, k, y - h, m) % m) % m
results[y] = ret
return ret
line = sys.stdin.readline().split()
x = int(line[0])
y = int(line[1])
m = int(line[2])
print(mod_exp(x, y, m))