Fibonacci Music

Time limit1sMemory limit512 MB

Summary
Build a digit string from Fibonacci numbers reduced mod M and answer queries for the N-th digit, with N up to 10^15.
Level

Hard8 of 10

Topics
Math, Number theory, Prefix sum, Binary search
Solved
No attempts yet

Problem

Cheolsu, a composer, happened to see a piano piece built from the Fibonacci sequence on YouTube. The Fibonacci sequence satisfies f1=1f_1 = 1, f2=1f_2 = 1, and fn+2=fn+1+fnf_{n+2} = f_{n+1} + f_n for all n≥1n \ge 1.

The piece was made by pressing the key corresponding to each digit of the Fibonacci sequence. If the piece uses the first 8 terms of the Fibonacci sequence, the keys are pressed 10 times in total, as follows.

1 → 1 → 2 → 3 → 5 → 8 → 1 → 3 → 2 → 1

Cheolsu decided to try this method himself. But the Fibonacci sequence grows so fast that it was hard for him to compute, since he is weak at addition.

So he changed the method a little. After choosing a number MM, he takes the remainder of each term of the Fibonacci sequence divided by MM, builds a new sequence from the individual digits of each number, and writes a piano piece from it.

For example, when M=10M=10, the new sequence is as follows.

{1, 1, 2, 3, 5, 8, 3, 1, …}

So Cheolsu presses keys in the order 1 → 1 → 2 → 3 → 5 → 8 → 3 → 1 → 4 → …

At this point, for a given NN, Cheolsu wondered about the number of the key pressed NN-th (that is, the NN-th term of the new sequence).

Given QQ values of NN as queries, write a program that outputs the number of the key pressed NN-th for each query.

Input

The first line gives the integers QQ and MM, separated by a space.

From the second line, QQ lines follow, each giving the integer NN that represents a query.

Output

For each NN, output the number of the key pressed NN-th (the NN-th term of the new sequence) on one line, in the order the queries appear in the input, for a total of QQ lines.

Constraints

  • 1≤N≤10151 \le N \le 10^{15}
  • 2≤M≤1,0002 \le M \le 1{,}000
  • 1≤Q≤100,0001 \le Q \le 100{,}000

Examples1

  1. Example 1

    Input
    2 10
    5
    8
    
    Expected output
    5
    1