T = int(input()) for i in range(T): N,M = map(int,input().split()) answer = N answer *= N+1 answer //= 2 answer %= M print(answer)