Jeffery found an amazing sequence of triples (a_k,b_k,c_k)_k=0∞:
For example, (a_1,b_1,c_1)=(5,2,1) and (a_2,b_2,c_2)=(29,12,5).
In modulo some integer p, 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 n and p (1≤n≤5000, 1≤p≤230) where n indicates the number of questions and p indicates all the following questions are in modulo p.
Each of the next n lines contains four integers x, y, z and m (0≤x,y,z<p, 0≤m≤1018) indicating a question that queries you to find the minimum integer k such that k≥m and (a_k,b_k,c_k)≡(x,y,z)(modp).
For each question, output in one line a single integer, indicating the answer to the question. If there is no such integer k, output −1 instead.
In the first sample, (a_0,b_0,c_0)≡(2,1,0), (a_1,b_1,c_1)≡(5,2,1), (a_2,b_2,c_2)≡(7,1,5), (a_2T+3,b_2T+3,c_2T+3)≡(6,1,4), (a_2T+4,b_2T+4,c_2T+4)≡(4,10,6) (mod11) where T=0,1,2,…
In the second sample, (a_0,b_0,c_0)≡(2,1,0), (a_1,b_1,c_1)≡(5,2,1), (a_2T+2,b_2T+2,c_2T+2)≡(9,2,5), (a_2T+3,b_2T+3,c_2T+3)≡(5,8,9) (mod10) where T=0,1,2,…