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() m = int(m) x = modulo(n, 2*m) x = (x*(x+1)) % (2*m) assert x % 2 == 0 print(x // 2) T = int(input()) for _ in range(T): solve()