import sys input = lambda :sys.stdin.readline()[:-1] ni = lambda :int(input()) na = lambda :list(map(int,input().split())) yes = lambda :print("yes");Yes = lambda :print("Yes") no = lambda :print("no");No = lambda :print("No") ####################################################################### for _ in range(ni()): n,m = na() n %= 2*m x = n * (n+1) // 2 print(x%m)