class Summation: def __init__(self, n, m): self.n = n self.m = m def calculate(self): n, m = self.n, self.m return ((n % m) * ((n + 1) % m) // 2) % m T = int(input()) for _ in range(T): N, M = map(int, input().split()) summation = Summation(N, M) print(summation.calculate())