import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean nonp[] = new boolean[5000001]; nonp[1] = true; for(int i = 2; i < 5000001; i++){ if(nonp[i]) continue; for(int j = i+i; j < 5000001; j += i){ nonp[j] = true; } } int t = Integer.parseInt(br.readLine()); while(t-- > 0){ String[] line = br.readLine().split(" "); long a = Long.parseLong(line[0]); int p = Integer.parseInt(line[1]); System.out.println(nonp[p] ? -1 : a%p==0 ? 0 : 1); } } }