import sys inv = [0, 1, 5, 0, 7, 2, 0, 4, 8, 0] def solve(lenS, x, a, b, m, inv): pow3 = 0 cum = 1 r = x ans = r % 10 if lenS == 1: return ans if ans == 0: all_zero = True else: all_zero = False for d in range(1, lenS): r = ((r ^ a) + b) % m s = r % 10 if s: all_zero = False n = lenS - d while not n % 3: pow3 += 1 n //= 3 while not d % 3: pow3 -= 1 d //= 3 cum = (cum * n * inv[d % 9]) % 9 if pow3 < 2: ans += cum * s * 3 ** pow3 if all_zero: return 0 return (ans - 1) % 9 + 1 T = int(input()) for line in sys.stdin: n, x, a, b, m = map(int, line.split()) print(solve(n, x, a, b, m, inv))