Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/sonlar-modul-teskari

Modular inverse

Medium 1000 ms 128 MB 49%
Share

You are given $q$ queries, each with positive integers $a$ and $m$. For every query find an integer $x$ with $0 \le x \lt m$ such that the remainder of $a \cdot x$ divided by $m$ equals $1$. If there is no such $x$, print $-1$. (If $x$ exists, it is unique.)

The number a and the modulus m; the x for which a times x leaves remainder one modulo m is highlighted

Input

The first line contains a positive integer $q$. Each of the next $q$ lines contains two positive integers: $a$ and $m$.

Output

For every query, on its own line, one integer — $x$ or $-1$.

Note

$1 \le q \le 10^{5}$
$1 \le a \le 10^{9}$
$2 \le m \le 10^{9}$

Examples

Input #1
3
3 11
2 4
10 17
Output #1
4
-1
12
Input #2
1
1 2
Output #2
1

Sign in to submit a solution

Signing up is free and takes a minute.