Created
January 8, 2018 06:05
-
-
Save komasaru/389caa790c42463a60069d9a49f39db7 to your computer and use it in GitHub Desktop.
Python script to compute modular-exponentiation iteratively.
This file contains 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
#! /usr/local/bin/python3.6 | |
""" | |
Modular Exponentiation (iterative) | |
""" | |
import sys | |
import traceback | |
class ModularExponentiation: | |
def comp_mod_exp(self, b, e, m): | |
""" Computation of modular exponentiation | |
:param int b: base | |
:param int e: exponent | |
:param int m: modulus | |
:return int me: modular expornentiation | |
""" | |
ans = 1 | |
try: | |
while e > 0: | |
if (e & 1) == 1: | |
ans = (ans * b) % m | |
e >>= 1 | |
b = (b * b) % m | |
return ans | |
except Exception as e: | |
raise | |
if __name__ == '__main__': | |
# me = b^e mod m | |
b, e, m = 12345, 6789, 4567 | |
try: | |
obj = ModularExponentiation() | |
me = obj.comp_mod_exp(b, e, m) | |
print("{}^{} mod {} = {}".format(b, e, m, me)) | |
except Exception as e: | |
traceback.print_exc() | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment