import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); Eratosthenes era = new Eratosthenes(5000000); PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < t; i++) { String[] sa = br.readLine().split(" "); long a = Long.parseLong(sa[0]); int p = Integer.parseInt(sa[1]); if (era.isSosuu(p)) { if (a % p == 0) { pw.println(0); } else { pw.println(1); } } else { pw.println(-1); } } br.close(); pw.flush(); } static class Eratosthenes { int[] div; public Eratosthenes(int n) { if (n < 2) return; div = new int[n + 1]; div[0] = -1; div[1] = -1; int end = (int) Math.sqrt(n) + 1; for (int i = 2; i <= end; i++) { if (div[i] == 0) { div[i] = i; for (int j = i * i; j <= n; j+=i) { if (div[j] == 0) div[j] = i; } } } for (int i = end + 1; i <= n; i++) { if (div[i] == 0) div[i] = i; } } public Map bunkai(int x) { Map soinsu = new HashMap<>(); while (x > 1) { Integer d = div[x]; if (soinsu.containsKey(d)) { soinsu.put(d, soinsu.get(d) + 1); } else { soinsu.put(d, 1); } x /= d; } return soinsu; } public boolean isSosuu(int x) { return div[x] == x; } } }