for _ in range(int(input())): n,m=map(int,input().split()) n1=n%m n2=(n+1)%m s=(n1*n2//2)%m print(s)