Skip to content

Instantly share code, notes, and snippets.

@gideongrinberg
Created June 9, 2021 01:25
Show Gist options
  • Save gideongrinberg/358fb0b53612b308e66c4d231b9102aa to your computer and use it in GitHub Desktop.
Save gideongrinberg/358fb0b53612b308e66c4d231b9102aa to your computer and use it in GitHub Desktop.
Modular exponentiation in AssemblyScript/Typescript.
/**
Modular exponentiation in AssemblyScript/TypeScript. Computes `a^b %n`.
Note that you'll likely need to change the int type. I'm using
the u128 (128-bit unsigned integer) from as-bignum.
@param a The base.
@param b The power.
@param n The modulus.
*/
export function powMod(a: u128, b: u128, n: u128): u128 {
a = a % n;
let result = 1;
let x = a;
while(b > 0) {
let leastSignificantBit = b % 2;
b = (b / 2) as u128;
if(leastSignificantBit == 1) {
result = result * x;
result = result % n;
}
x = x * x;
x = x % n;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment