Eventually Periodic Sequence
Time limit1sMemory limit128 MB
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 , a function is given, together with a non-negative integer . From these one can build the infinite sequence , where is defined recursively by and .
Every such sequence is eventually periodic: from some point onward it repeats, for example .
Given , , and the function , compute the period of the sequence .
Input
Each line of input contains , , and a description of in postfix notation, also known as Reverse Polish Notation (RPN). The operands are unsigned integer constants, the letter , or the variable . 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 , whose value is read from the input. For example, the RPN expression
2 x * 7 + N %
is the more familiar infix . Every input line is shorter than 100 characters. The last line of input has and must not be processed.
Output
For each line of input, output one line containing a single integer: the period of the sequence that corresponds to the data on that input line.