This page is still under construction.

Parts of this page are still being built. What you see may change.

Fraction

Time limit3sMemory limit256 MB

Summary
For each current game count a, find the smallest A >= 0 with a + A <= M such that some fraction with denominator a + A terminates in base B.
Level

Medium7 of 10

Topics
Number theory, Math, Binary search, Brute force
Solved
No attempts yet

Problem

During his first days in the mental ward, Berlaga pretended to be the viceroy of India. After giving it some thought, he decided it was risky. They could put him on an elephant and make him steer the beast through the streets. He opted for a change of story. He has not decided yet what his next persona will be. Meanwhile, he is enjoying his favorite pastime: playing Solitaire.

Every now and then, he begins to wonder: what portion of the games does he win? Solitaire itself provides the answer with only two decimal places, and Berlaga loves precision and sometimes calculates the proportion himself. The answer can be either a terminating or a repeating fraction, depending on the proportion itself and on the base of the numeral system used. That is right, mad accountants can use any positional numeral system they want, not only decimal. For instance, in the decimal system, 1/31/3 is an infinite repeating fraction, and 4/104/10 is a terminating fraction, however, in the ternary numeral system, everything is the other way around: 1/31/3 is a terminating fraction "0.10.1", and 4/104/10 is an infinite recurring fraction "0.101210121012…0.101210121012\ldots".

Naturally, like all accountants, he does not like infinite fractions and prefers to calculate the proportion of his wins only when he is absolutely sure that it will be a terminating fraction. To do this, he needs to play a few more games.

Help Berlaga find the minimal number of games to be played additionally. The total number of played games must not be greater than MM.

Input

The first line of the input file contains three numbers: BB, the base of the numeral system, MM, the maximum allowed number of games, and NN, the number of queries (2≤B≤5⋅1062 \le B \le 5 \cdot 10^6, 1≤M≤10181 \le M \le 10^{18}, 1≤N≤1051 \le N \le 10^5).

The next NN lines describe the queries. Each line contains a single integer aia_i, the number of games already played by Berlaga (1≤ai≤M1 \le a_i \le M).

Output

The output file must contain NN lines, with an answer to the corresponding query in each line. Each answer must be an integer AA, the number of games to be played additionally to ensure that the proportion of wins is a terminating fraction (A≥0A \ge 0). If the total number of games in this case is greater than MM, print −1-1 as the answer.

Examples1

  1. Example 1

    Input
    100 120 3
    5
    117
    13
    
    Expected output
    0
    -1
    3