import sys sys.set_int_max_str_digits(4*10**6) class Summation: def __init__(self, n, m): self.n = n self.m = m def calculate(self): n, m = self.n, self.m n1 = n % m n2 = (n + 1) % m if n % 2 == 0: return ((n // 2) % m * n2) % m else: return (n1 * ((n + 1) // 2) % m) % m T = int(input()) for _ in range(T): N, M = map(int, input().split()) summation = Summation(N, M) print(summation.calculate())