Skip to content

Instantly share code, notes, and snippets.

@adrian154
Created October 28, 2023 05:26
Show Gist options
  • Save adrian154/edf64b048568bad48d9f650d7068fd00 to your computer and use it in GitHub Desktop.
Save adrian154/edf64b048568bad48d9f650d7068fd00 to your computer and use it in GitHub Desktop.
// Efficient modular exponentiation using BigInts
// Based on pseudocode from https://en.wikipedia.org/wiki/Modular_exponentiation
// !! NEVER use this method for actual cryptographic applications !!
const powMod = (base, exponent, modulus) => {
if(modulus == 1n) {
return 0n;
}
let result = 1n;
base = base % modulus;
while(exponent > 0n) {
if(exponent % 2n == 1n) {
result = (result * base) % modulus;
}
exponent >>= 1n;
base = (base * base) % modulus;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment