use std::io::{BufRead, Write}; const PMAX: usize = 5_000_000; fn main () { let stdin = std::io::stdin(); let stdout = std::io::stdout(); let mut reader = std::io::BufReader::new(stdin.lock()); let mut writer = std::io::BufWriter::new(stdout.lock()); let mut prime_table = vec![true; PMAX + 1]; prime_table[1] = false; for i in 2..=PMAX { if !prime_table[i] { continue; } let mut j = i + i; while j <= PMAX { prime_table[j] = false; j += i; } } let t: usize = { let mut buf = String::new(); reader.read_line(&mut buf).unwrap(); buf.trim_end().parse().unwrap() }; for _ in 0..t { let (a, p): (usize, usize) = { let mut buf = String::new(); reader.read_line(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) }; if prime_table[p] { writeln!(writer, "{}", a % p).unwrap(); } else { writeln!(writer, "-1").unwrap(); } } }