Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Created August 23, 2018 01:56
Show Gist options
  • Save Radcliffe/e41b41a441deda19e7ac5731197f49be to your computer and use it in GitHub Desktop.
Save Radcliffe/e41b41a441deda19e7ac5731197f49be to your computer and use it in GitHub Desktop.
Fast modular exponentiation in Erlang
-module(powermod).
-export([powmod/2]).
powmod(A, B, M) -> powmod(A, B, M, 1).
powmod(_, 0, _, R) -> R;
powmod(A, B, M, R) when B rem 2 == 1 -> powmod(A, B-1, M, A*R rem M);
powmod(A, B, M, R) -> powmod(A*A rem M, B div 2, M, R).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment