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