Mysterious Triple Sequence

아직 제출이 없습니다시간 제한6초메모리 제한256 MB

문제

Jeffery found an amazing sequence of triples (a_k,b_k,c_k)_k=0\\{(a\_k, b\_k, c\_k)\\}\_{k = 0}^{\infty}:

  1. (a_0,b_0,c_0)=(2,1,0)(a\_0, b\_0, c\_0) = (2, 1, 0).
  2. For each non-negative integer kk, (a_k+1,b_k+1,c_k+1)=(a_k2+b_k2,a_kb_k+b_kc_k,b_k2+c_k2)(a\_{k + 1}, b\_{k + 1}, c\_{k + 1}) = (a\_k^2 + b\_k^2, a\_k b\_k + b\_k c\_k, b\_k^2 + c\_k^2).

For example, (a_1,b_1,c_1)=(5,2,1)(a\_1, b\_1, c\_1) = (5, 2, 1) and (a_2,b_2,c_2)=(29,12,5)(a\_2, b\_2, c\_2) = (29, 12, 5).

In modulo some integer pp, some triples would never appear in this sequence, some triples would appear periodically and other triples would appear only once.

Jeffery is wondering if you could help him find out the first appearance of some triples starting from given positions. Could you help him, please?

입력

The first line contains two integers nn and pp (1n50001 \leq n \leq 5000, 1p2301 \leq p \leq 2^{30}) where nn indicates the number of questions and pp indicates all the following questions are in modulo pp.

Each of the next nn lines contains four integers xx, yy, zz and mm (0x,y,z<p0 \leq x, y, z < p, 0m10180 \leq m \leq 10^{18}) indicating a question that queries you to find the minimum integer kk such that kmk \geq m and (a_k,b_k,c_k)(x,y,z)(modp)(a\_k, b\_k, c\_k) \equiv (x, y, z) \pmod{p}.

출력

For each question, output in one line a single integer, indicating the answer to the question. If there is no such integer kk, output 1-1 instead.

힌트

In the first sample, (a_0,b_0,c_0)(2,1,0)(a\_0, b\_0, c\_0) \equiv (2, 1, 0), (a_1,b_1,c_1)(5,2,1)(a\_1, b\_1, c\_1) \equiv (5, 2, 1), (a_2,b_2,c_2)(7,1,5)(a\_2, b\_2, c\_2) \equiv (7, 1, 5), (a_2T+3,b_2T+3,c_2T+3)(6,1,4)(a\_{2 T + 3}, b\_{2 T + 3}, c\_{2 T + 3}) \equiv (6, 1, 4), (a_2T+4,b_2T+4,c_2T+4)(4,10,6)(a\_{2 T + 4}, b\_{2 T + 4}, c\_{2 T + 4}) \equiv (4, 10, 6) (mod11)\pmod{11} where T=0,1,2,T = 0, 1, 2, \ldots

In the second sample, (a_0,b_0,c_0)(2,1,0)(a\_0, b\_0, c\_0) \equiv (2, 1, 0), (a_1,b_1,c_1)(5,2,1)(a\_1, b\_1, c\_1) \equiv (5, 2, 1), (a_2T+2,b_2T+2,c_2T+2)(9,2,5)(a\_{2 T + 2}, b\_{2 T + 2}, c\_{2 T + 2}) \equiv (9, 2, 5), (a_2T+3,b_2T+3,c_2T+3)(5,8,9)(a\_{2 T + 3}, b\_{2 T + 3}, c\_{2 T + 3}) \equiv (5, 8, 9) (mod10)\pmod{10} where T=0,1,2,T = 0, 1, 2, \ldots