Power towers

Given lists of positive integers, compute each power tower modulo M, where the tower can be astronomically large.

Hard8Number theoryRecursionMathImplementationNo attempts yetTime limit2sMemory limit512 MB

Problem

You are given a non-empty list of positive integers [x1,x2,,xN][x_1, x_2, \dots, x_N]. The power tower of this list is the number

x1x2xNx_1^{x_2^{\cdot^{\cdot^{\cdot^{x_N}}}}}

The exponents are evaluated from the top down, so the value is x1(x2(xN))x_1^{\left(x_2^{\left(\cdots^{x_N}\right)}\right)}.

A power tower grows very large even when the list holds only a few small integers. The power tower of [2,3,2][2, 3, 2] is 232=29=5122^{3^2} = 2^9 = 512, and the power tower of [5,2,3,2][5, 2, 3, 2] is 55125^{512}, which has 358 decimal digits.

Compute each power tower modulo a given positive integer MM.

Input

The first line contains two positive integers TT and MM. Each of the next TT lines contains a positive integer NN followed by NN positive integers x1,x2,,xNx_1, x_2, \dots, x_N. Consecutive numbers on a line are separated by exactly one space.

Output

Print TT lines. Line kk contains the power tower of the kk-th list modulo MM.

Constraints

  • 1T10001 \le T \le 1000
  • The lengths NN of all lists sum to at most 10610^6.
  • 1xi1061 \le x_i \le 10^6
  • 1M1091 \le M \le 10^9

Hint

When M=10M = 10, the answer for each list is the last decimal digit of its power tower. Most of the lists in the sample input have a power tower too large to fit in a 32-bit or 64-bit integer.