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(i -> { char[] input = sc.next().toCharArray(); int m = sc.nextInt(); int length = input.length; long base = 0; long half = 0; boolean isOdd = false; for (char c : input) { int x = c - '0'; base *= 10; base += x; base %= m; half *= 10; half += isOdd ? 5 : 0; half += x / 2; half %= m; isOdd = (x % 2 == 1); } if (isOdd) { half++; } else { base++; } return String.valueOf(base * half % m); }).collect(Collectors.joining("\n")); System.out.println(result); } } 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(); } } }