Skip to content

Instantly share code, notes, and snippets.

@tomato42
Created November 19, 2016 14:19
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 tomato42/a07300895ab0b98c4761cd318e2d6304 to your computer and use it in GitHub Desktop.
Save tomato42/a07300895ab0b98c4761cd318e2d6304 to your computer and use it in GitHub Desktop.
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