import sys input = sys.stdin.readline T=int(input()) for tests in range(T): N,M=map(int,input().split()) print((N*(N+1)//2)%M)