import sys inf = float("inf") # sys.setrecursionlimit(10**6) input = lambda: sys.stdin.readline().rstrip("\r\n") print = lambda *args, end="\n", sep=" ": sys.stdout.write( sep.join(map(str, args)) + end ) def II(): return int(input()) def MII(b=0): return map(lambda x: int(x) - b, input().split()) def LII(b=0): return list(MII(b)) for _ in range(II()): x, m = LII() y = x + 1 if x & 1: y //= 2 else: x //= 2 print((x % m) * (y % m) % m)