#abc270g. G - Sequence in mod P

G - Sequence in mod P

Score : 600600 points

问题描述

存在一个序列 X=(X0,X1,)X=(X_0, X_1, \ldots),由以下递推关系定义。

$X_i = \left\{ \begin{array}{ll} S & (i = 0)\\ (A \times X_{i-1}+B) \bmod P & (i \geq 1) \end{array} \right.$

确定是否存在某个 ii 使得 Xi=GX_i=G。如果存在,找出最小的这样的 ii 值。

此处,xmodyx \bmod y 表示 xx 除以 yy 后的余数(最小非负剩余数)。

对于每个输入文件,你将得到 TT 个测试用例。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

There is a sequence X=(X0,X1,)X=(X_0, X_1, \ldots) defined by the following recurrence relation.

$X_i = \left\{ \begin{array}{ll} S & (i = 0)\\ (A X_{i-1}+B) \bmod P & (i \geq 1) \end{array} \right.$

Determine whether there is an ii such that Xi=GX_i=G. If it exists, find the smallest such ii.
Here, xmodyx \bmod y denotes the remainder when xx is divided by yy (the least non-negative residue).

You are given TT test cases for each input file.

Constraints

  • 1T1001 \leq T \leq 100
  • 2P1092 \leq P \leq 10^9
  • PP is a prime.
  • 0A,B,S,G<P0\leq A,B,S,G < P
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

TT

case1\mathrm{case}_1

case2\mathrm{case}_2

\vdots

caseT\mathrm{case}_T

Each test case is in the following format:

PP AA BB SS GG

Output

Print TT lines.
The tt-th line should contain the smallest ii such that Xi=GX_i=G for caset\mathrm{case}_t, or -1 if there is no such ii.

Sample Input 1

3
5 2 1 1 0
5 2 2 3 0
11 1 1 0 10

Sample Output 1

3
-1
10

For the first test case, we have X=(1,3,2,0,)X=(1,3,2,0,\ldots), so the smallest ii such that Xi=0X_i=0 is 33.
For the second test case, we have X=(3,3,3,3,)X=(3,3,3,3,\ldots), so there is no ii such that Xi=0X_i=0.

update @ 2024/3/10 11:24:23