Skip to content

Instantly share code, notes, and snippets.

@theabbie
Last active April 10, 2022 03:50
Show Gist options
  • Save theabbie/8ed9a5c1887d2fd5463b423aaf5f485a to your computer and use it in GitHub Desktop.
Save theabbie/8ed9a5c1887d2fd5463b423aaf5f485a to your computer and use it in GitHub Desktop.
Modular exponentiation by squaring algorithm
# modexp(b, n, M) => (b ^ n) % M
def modexp(b, n, M):
if n == 0:
return 1 % M
k = modexp(b, n >> 1, M) ** 2
if n & 1:
return (b * k) % M
else:
return k % M
print(modexp(23, 67, 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment