T = int(input()) def sigma(n, m): r = (n*(n+1)//2)%m return r for i in range(T): N, M = map(int, input().split()) ans = sigma(N, M) print(ans)