Eventually Periodic Sequence

Time limit1sMemory limit128 MB

Summary
Given N, a start n, and a function f written in postfix, follow the iteration x -> f(x) mod N and report the length of its eventual cycle.
Level

Medium7 of 10

Topics
Math, Simulation, Implementation, Hash map
Solved
No attempts yet

Problem

For a non-negative integer NN, a function f ⁣:{0,1,…,N}→{0,1,…,N}f\colon \{0, 1, \dots, N\} \to \{0, 1, \dots, N\} is given, together with a non-negative integer n≤Nn \le N. From these one can build the infinite sequence F=f1(n),f2(n),…,fk(n),…F = f^{1}(n), f^{2}(n), \dots, f^{k}(n), \dots, where fk(n)f^{k}(n) is defined recursively by f1(n)=f(n)f^{1}(n) = f(n) and fk+1(n)=f(fk(n))f^{k+1}(n) = f(f^{k}(n)).

Every such sequence FF is eventually periodic: from some point onward it repeats, for example 1,2,7,5,4,6,5,4,6,5,4,6,…1, 2, 7, 5, 4, 6, 5, 4, 6, 5, 4, 6, \dots.

Given N≤11000000N \le 11000000, n≤Nn \le N, and the function ff, compute the period of the sequence FF.

Input

Each line of input contains NN, nn, and a description of ff in postfix notation, also known as Reverse Polish Notation (RPN). The operands are unsigned integer constants, the letter NN, or the variable xx. Only binary operators are allowed: ++ (addition), \*\* (multiplication), and %\% (modulo, i.e. the remainder of integer division). Operands and operators are separated by whitespace. The %\% operator occurs exactly once in each function and is always the last (rightmost, or topmost) operator, and its second operand is always NN, whose value is read from the input. For example, the RPN expression

2 x * 7 + N %

is the more familiar infix (2\*x+7)%N(2 \* x + 7) \% N. Every input line is shorter than 100 characters. The last line of input has N=0N = 0 and must not be processed.

Output

For each line of input, output one line containing a single integer: the period of the sequence FF that corresponds to the data on that input line.

Examples1

  1. Example 1

    Input
    10 1 x N %
    11 1 x x 1 + * N %
    1728 1 x x 1 + * x 2 + * N %
    1728 1 x x 1 + x 2 + * * N %
    100003 1 x x 123 + * x 12345 + * N %
    0 0 0 N %
    
    Expected output
    1
    3
    6
    6
    369