Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created January 8, 2018 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/389caa790c42463a60069d9a49f39db7 to your computer and use it in GitHub Desktop.
Save komasaru/389caa790c42463a60069d9a49f39db7 to your computer and use it in GitHub Desktop.
Python script to compute modular-exponentiation iteratively.
#! /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