Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Modular exponentiation
from __future__ import print_function
import sys
import getopt
import math
g = None
e = None
m = None
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "g:e:m:")
for opt, arg in opts:
if opt == '-g':
g = int(arg)
elif opt == '-e':
e = int(arg)
elif opt == '-m':
m = int(arg)
else:
raise Exception("Unrecognised option: {0}".format(opt))
if args:
raise Exception("Not matching options: {0}".format(args))
if e is None:
e = m
if not all((g, e, m)):
raise Exception("Must specify at least -g and -m, neither can be zero")
for i in range(e):
print("{0}^{1:<{width}} mod {2} = {3}".format(g, i, m, pow(g, i, m),
width=int(math.ceil(math.log10(e)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment