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