From e8251c2aade90f8f5fa8b562411374bc1ba6b18e Mon Sep 17 00:00:00 2001 From: tommi27 Date: Tue, 2 Apr 2019 16:01:04 +0200 Subject: [PATCH] did modular exponentiation with high level of ignorance (mooooooooo tablet, see problem F) --- modular_exponentiation.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/modular_exponentiation.py b/modular_exponentiation.py index 49dc8e7..7a6683b 100644 --- a/modular_exponentiation.py +++ b/modular_exponentiation.py @@ -3,10 +3,24 @@ import sys def mod_exp(x, y, m): k = x % m - for i in range(y): - print(i) - k = (k * x) % m - return k + 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])