import java.io.*; import java.util.*; import java.util.function.*; import java.util.stream.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int t = sc.nextInt(); String result = IntStream.range(0, t).mapToObj(a -> { char[] n = sc.next().toCharArray(); int mod = sc.nextInt(); long ans; if ((n[n.length - 1] - '0') % 2 == 0) { ans = halfValue(n, mod); n[n.length - 1]++; ans *= fullValue(n, mod); ans %= mod; } else { ans = fullValue(n, mod); n[n.length - 1]++; ans *= halfValue(n, mod); ans %= mod; } return String.valueOf(ans); }).collect(Collectors.joining("\n")); System.out.println(result); } static long halfValue(char[] arr, int mod) { long ans = 0; int next = 0; for (char c : arr) { int x = c - '0' + next; ans *= 10; ans += x / 2; ans %= mod; next = x % 2 * 10; } return ans; } static long fullValue(char[] arr, int mod) { long ans = 0; for (char c : arr) { ans *= 10; ans += c - '0'; ans %= mod; } return ans; } } class Scanner { BufferedReader br; StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); public Scanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); } catch (Exception e) { } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { try { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (Exception e) { e.printStackTrace(); } finally { return st.nextToken(); } } }