Fast modular powers

RSA and Diffie-Hellman both need b^e mod m for huge e. Repeated squaring gets there in about log₂(e) steps, keeping every number small.

What to build

For each line b e m, print b^e mod m.

Requirements

  • Use repeated squaring: square the base each step, and multiply it into the result when the current bit of e is 1.
  • Reduce modulo m after every multiplication.
  • b^0 mod m is 1 mod m (so it is 0 when m is 1).

Input

One triple b e m per line.

Output

One number per line.

Constraints

0 ≤ b, e ≤ 10¹⁸ and 1 ≤ m ≤ 10⁹. Products can be bigger than JavaScript's safe whole numbers, so use BigInt.

Example

Input:

65 17 3233
2790 2753 3233

Output:

2790
65

Why it works

Writing e in binary splits b^e into a product of b^1, b^2, b^4, … for the 1 bits, and each of those is the square of the one before, so about log₂(e) squarings are enough.

Examples

Example 1 · Input
65 17 3233
2790 2753 3233
Expected output
2790
65
Example 2 · Input
5 6 23
2 10 1000
Expected output
8
24

Hints

Hint 1

BigInt("123") makes a BigInt; write 1n, 2n for BigInt literals.

Hint 2

while (e > 0n) { if (e & 1n) ...; b = b * b % m; e >>= 1n; }

Solution

Show one correct solution (try it yourself first)
function modPow(b, e, m) {
  let result = 1n % m;
  b %= m;
  while (e > 0n) {
    if (e & 1n) result = (result * b) % m;
    b = (b * b) % m;
    e >>= 1n;
  }
  return result;
}
let line = prompt();
while (line !== null) {
  const [b, e, m] = line.trim().split(/\s+/).map(BigInt);
  console.log(String(modPow(b, e, m)));
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Public-key encryption with toy RSA →