Last active
August 22, 2018 08:22
-
-
Save nitinbhojwani/e94ac596d367b1d2c4f50bc16f489af5 to your computer and use it in GitHub Desktop.
Multiplication and Power Modulo operations for large numbers in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| cal_add_mod_dict = {} | |
| cal_sub_mod_dict = {} | |
| cal_mul_mod_dict = {} | |
| cal_pow_mod_dict = {} | |
| def cal_add_mod(a, b, n): | |
| """Calculates (a+b) mod n""" | |
| t = (a,b,n) | |
| if t not in cal_add_mod_dict: | |
| cal_add_mod_dict[t] = (a % n + b % n) % n | |
| return cal_add_mod_dict[t] | |
| def cal_sub_mod(a, b, n): | |
| """Calculates (a-b) mod n""" | |
| t = (a,b,n) | |
| if t not in cal_sub_mod_dict: | |
| cal_sub_mod_dict[t] = (a % n - b % n) % n | |
| return cal_sub_mod_dict[t] | |
| def cal_mul_mod(a, b, n): | |
| """Calculates (a * b) mod n""" | |
| t = (a,b,n) | |
| if t not in cal_mul_mod_dict: | |
| if a > n: | |
| a = a%n | |
| if b > n: | |
| b = b%n | |
| c = (a * b) // n | |
| r = (a * b - c * n) % n | |
| r = r + m if r < 0 else r | |
| cal_mul_mod_dict[t] = r | |
| return cal_mul_mod_dict[t] | |
| def cal_pow_mod(a, k, n): | |
| """Calculates (a to power k) mod n""" | |
| t = (a,k,n) | |
| if t not in cal_pow_mod_dict: | |
| r = 0 if n == 1 else 1 | |
| while k > 0: | |
| if k & 1: | |
| r = cal_mul_mod(r, a, n) | |
| k = k >> 1; | |
| a = cal_mul_mod(a, a, n); | |
| cal_pow_mod_dict[t] = r | |
| return cal_pow_mod_dict[t] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment