import sys sys.set_int_max_str_digits(0) for _ in range(int(input())): N,M=map(int,input().split()) N%=M print(N*(N+1)//2%M)