Eavesdrop on a tiny exchange

With a tiny prime, an eavesdropper who sees p, g, A and B can try every possible secret until g^x mod p equals A.

What to build

Find Anika's secret from the public values by trying every exponent, then compute the shared key.

Requirements

  • Try x = 1, 2, … up to p − 1 and take the first x with g^x mod p = A.
  • Print a x and then key k, where k = B^x mod p.
  • If no x works, print no secret found.

Input

One line: p g A B.

Output

Two lines, or one.

Constraints

p is a prime up to 100000, and 1 ≤ g, A, B < p.

Example

Input:

23 5 8 19

Output:

a 6
key 2

Why it works

The search needs at most p − 1 tries, which is fast only because p is tiny; with a 2048-bit prime the same search is hopeless, which is what keeps real exchanges safe.

Examples

Example 1 · Input
23 5 8 19
Expected output
a 6
key 2
Example 2 · Input
23 5 10 4
Expected output
a 3
key 18

Hints

Hint 1

Keep a running power: power = power * g % p each step, instead of recomputing g^x from scratch.

Hint 2

The first x that matches is enough: any x with g^x = A gives the same key.

Solution

Show one correct solution (try it yourself first)
const [p, g, A, B] = prompt().trim().split(/\s+/).map(Number);
let power = 1;
let found = -1;
for (let x = 1; x < p; x++) {
  power = (power * g) % p;
  if (power === A) {
    found = x;
    break;
  }
}
if (found < 0) console.log("no secret found");
else {
  let key = 1;
  for (let k = 0; k < found; k++) key = (key * B) % p;
  console.log(`a ${found}`);
  console.log(`key ${key}`);
}

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

Lesson: Agreeing on a key: Diffie-Hellman →