Fraction
Time limit3sMemory limit256 MB
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, is an infinite repeating fraction, and is a terminating fraction, however, in the ternary numeral system, everything is the other way around: is a terminating fraction "", and is an infinite recurring fraction "".
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 .
Input
The first line of the input file contains three numbers: , the base of the numeral system, , the maximum allowed number of games, and , the number of queries (, , ).
The next lines describe the queries. Each line contains a single integer , the number of games already played by Berlaga ().
Output
The output file must contain lines, with an answer to the corresponding query in each line. Each answer must be an integer , the number of games to be played additionally to ensure that the proportion of wins is a terminating fraction (). If the total number of games in this case is greater than , print as the answer.