text: def solve(a, n, m):
      a = a % m
      pow10 = 10 ** len(str(a)) % m
      answer = 0
  
      while n:
          if n & 1:  # ie n is odd number
              answer = ((answer * pow10) % m + a) % m
  
          a = ((a * pow10) % m + a) % m
          pow10 = (pow10 * pow10) % m
          n >>= 1
  
      return answer
  
  
  t = int(input())
  for _4 in range(0, t):
      arr = list(map(int, input().split()))
      a = arr[0]
      m = arr[1]
      ans = solve(1, a, m)
      print(ans)
  