#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void exgcd(ll a, ll b, ll &d, ll &x, ll &y)
{
    b == 0 ? (x = 1, y = 0, d = a) : (exgcd(b, a % b, d, y, x), y -= x * (a / b));
}
int main()
{
    int T, a, m;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d", &a, &m);
        ll d, x, y;
        exgcd(a, m, d, x, y);
        if (d != 1)
            puts("Not Exist");
        else
            printf("%lld\n", m == 1 ? 1 : (x % m + m) % m);
    }
    return 0;
}
