This Can't Go On Forever

Time limit1sMemory limit128 MB

Summary
For each modulus m up to 2^24, output the length of the Pisano period of the Fibonacci sequence modulo m.
Level

Hard8 of 10

Topics
Number theory, Math, Implementation, Brute force
Solved
No attempts yet

Problem

Long ago, in a galaxy far, far away, there was a world whose favorite pet — the taye — reproduced by budding. Once a young taye separated from its parent, it needed exactly one unit of time to mature, which is also exactly how long a fresh bud takes to grow and separate from its parent. Tayes live practically forever, so their owners like to count how many they will eventually have. Suppose that at time 00 you own no taye, and at time 11 a friend gives you a single freshly budded (still immature) taye.

The number of tayes you own then follows the recurrence

T(0)=0,T(1)=1,T(n)=T(n−1)+T(n−2) for n>1.T(0) = 0, \quad T(1) = 1, \quad T(n) = T(n-1) + T(n-2) \ \text{for } n > 1.

These are the Fibonacci numbers. If the recurrence is computed under a fixed modulus mm (every value taken modulo mm), the sequence of remainders eventually starts repeating. The question is: how long is one full period before it repeats?

The first few sequences look like this:

ModulusStart of the sequence under that modulusPeriod length
20 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 13
30 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 28
40 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 36
50 1 1 2 3 0 3 3 1 4 0 4 4 3 2 0 2 2 4 1 0 1 120

For each modulus given in the input, determine the length of the smallest period of this sequence and report it.

Input

The input contains an unknown number of lines. Each line holds a single integer mm with 2≤m≤167772162 \le m \le 16777216 (that is, 2242^{24}). The final line contains 00, which marks the end of the input and must not be processed.

Output

For each modulus mm in the input, print the modulus, a single space, and then the length of the smallest period of the Fibonacci sequence taken modulo mm.

Examples1

  1. Example 1

    Input
    2
    3
    4
    5
    6
    12345678
    16777216
    0
    
    Expected output
    2 3
    3 8
    4 6
    5 20
    6 24
    12345678 700512
    16777216 25165824