#include <bits/stdc++.h>
#define REP(i, s, n) for (int i = s; i < (int)(n); i++)
#define ALL(a) a.begin(), a.end()
#define MOD 1000000007
using namespace std;
using ll = long long;

const int N = 5e6;
vector<bool> primes(N + 1, true);
void init() {
    primes[0] = primes[1] = false;
    for (int i = 2; i * i <= N; i++) {
        if (!primes[i]) continue;
        for (int j = 2 * i; j <= N; j += i) primes[j] = false;
    }
}

int main() {
    init();

    int T; cin >> T;
    while (T--) {
        ll A; int P; cin >> A >> P;
        if (primes[P]) {
            cout << (A % P == 0 ? 0 : 1) << endl;
        } else {
            cout << -1 << endl;
        }
    } 
    return 0;
}