import sys sys.set_int_max_str_digits(0) t = int(input()) def nC2(n): return n*(n+1)//2 for _ in range(t): n,m = map(int,input().split()) p = n//m d = n%m p %= m ans = (nC2(m-1) * p + nC2(d))%m print(ans)