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