import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) def factor(n, m=None): # mを与えると、高々その素因数まで見て、残りは分解せずにそのまま出力する f = {} tmp = n M = int(-(-n**0.5//1))+1 if m is not None: M = min(m+1, M) for i in range(2, M+1): if tmp=2: ans = 0 elif n>=m: ans = 0 else: ans = -1 for i in range(n+1,m)[::-1]: ans *= pow(i,m-2,m) ans %= m return ans%m t = int(input()) for i in range(t): n,m = list(map(int, input().split())) print(sub(n,m))