for _ in range(int(input())): n, b = map(int, input().split()) a = [list(map(int, input().split())), list(map(int, input().split()))] x = abs(a[0][0] * a[1][1] - a[0][1] * a[1][0]) ans = (n % b if x == 1 else (pow(x, n, b * (x - 1)) - 1) // (x - 1) % b) print(ans * x % b)