Gold Coin Game
Time limit1sMemory limit128 MB
Given S coins and a legal move set of powers of K, find the smallest first move that guarantees a win for the starting player, or 0 if none exists.
- Level
Medium7 of 10
- Topics
- Game theory, Math, Dynamic programming
- Solved
- No attempts yet
Problem
Being a pirate looks like a wonderful profession, but it has its hardships. One of them is spending long stretches of time on the open sea on days when nothing happens at all. To fight the boredom, pirates know many games played with gold coins.
In one such game, two pirates play over a single pile of gold coins. They take turns one after another. On a turn, for a given integer , a pirate may take a number of coins equal to a power of , i.e. one of (but never more than the coins that remain). The pirate who takes the last coin wins.
Given the number of coins currently in the pile and the value , determine the minimum number of coins the first pirate must take on the very first turn in order to be guaranteed a win. Both pirates play optimally.
Input
The first line contains the number of test cases.
Each test case consists of a single line with two integers and . Here is the number of coins, and means that on each turn a pirate may take coins. (, )
Output
For each test case, print on one line the minimum number of coins the first pirate must take on the first turn in order to win. If the first pirate cannot win no matter how many coins are taken, print .