T = int(input()) for _ in range(T): N, M = input().split() M = int(M) h = 0 m = 0 for i in range(len(N)): m = m*10+int(N[i]) h = (h*10+m//2)%M m %= 2 m += 1 if m == 2: m = 0 h += 1 n = 0 for i in range(len(N)): n = (n*10+int(N[i]))%M print((h*n+(n-h)*m)%M)