Modular inverse

RSA's private exponent d is the inverse of e modulo φ(n): the number with e × d leaving remainder 1. The extended Euclidean algorithm finds it.

What to build

For each pair e m, print the inverse of e modulo m, or say that there is none.

Requirements

  • The inverse is the number d from 0 to m − 1 with (e × d) mod m = 1.
  • It exists only when e and m share no common factor (gcd 1). Otherwise print none.
  • Use the extended Euclidean algorithm, not a search through every d.

Input

One pair e m per line.

Output

One line per pair: the inverse or none.

Constraints

2 ≤ m ≤ 10¹⁵ and 0 ≤ e < m. Use BigInt or keep the numbers within safe whole numbers.

Example

Input:

17 3120
3 7

Output:

2753
5

Why it works

Euclid's algorithm keeps writing each remainder as a combination s × e + t × m. When the remainder reaches 1, s × e = 1 (mod m), so s, made positive, is the inverse; if the last non-zero remainder is not 1, they share a factor and no inverse exists.

Examples

Example 1 · Input
17 3120
3 7
Expected output
2753
5
Example 2 · Input
15 3120
1 2
Expected output
none
1

Hints

Hint 1

Track (old_r, r) and (old_s, s), starting from (e, m) and (1, 0).

Hint 2

At the end, if old_r is 1 the answer is ((old_s % m) + m) % m.

Solution

Show one correct solution (try it yourself first)
function inverse(e, m) {
  let [r0, r1] = [e, m];
  let [s0, s1] = [1n, 0n];
  while (r1 !== 0n) {
    const q = r0 / r1;
    [r0, r1] = [r1, r0 - q * r1];
    [s0, s1] = [s1, s0 - q * s1];
  }
  return r0 === 1n ? ((s0 % m) + m) % m : null;
}
let line = prompt();
while (line !== null) {
  const [e, m] = line.trim().split(/\s+/).map(BigInt);
  const d = inverse(e, m);
  console.log(d === null ? "none" : String(d));
  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 →