def modulo(s: str, m: int) -> int: x = 0 for d in map(int, s): x = (10*x + d) % m return x def solve(): n, m = input().split() m2 = int(m) * 2 x = modulo(n, m2) x = (x * (x+1)) % m2 assert x % 2 == 0 print(x // 2) T = int(input()) for _ in range(T): solve()