import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; public class EXPotentiaLLL { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); private static StringTokenizer st; private static int readInt() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } private static Long readLong() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public static void main(String[] args) throws IOException { int T = readInt(); while (T-- > 0) pw.println(solve()); pw.close(); } static boolean[] INITIAL_PRIMES = initialPrimes(); private static long solve() throws IOException { long A = readLong(); int P = readInt(); if (!INITIAL_PRIMES[P]) return -1; if (A % P == 0) return 0; else return 1; } private static boolean[] initialPrimes() { boolean[] isPrime = new boolean[5000000]; for (int i = 3; i < 5000000; i += 2) { isPrime[i] = true; } for (int p = 3, squareRoot = (int) Math.sqrt(5000000); p <= squareRoot; p += 2) { if (isPrime[p]) { for (int j = p * p; j < 5000000; j += p) isPrime[j] = false; } } return isPrime; } }