Gold Coin Game

Time limit1sMemory limit128 MB

Summary
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 KK, a pirate may take a number of coins equal to a power of KK, i.e. one of 1,K,K2,K3,…1, K, K^2, K^3, \dots (but never more than the coins that remain). The pirate who takes the last coin wins.

Given the number of coins SS currently in the pile and the value KK, 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 SS and KK. Here SS is the number of coins, and KK means that on each turn a pirate may take 1,K,K2,…1, K, K^2, \dots coins. (1≤S≤1091 \le S \le 10^9, 1≤K≤1001 \le K \le 100)

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 00.

Examples1

  1. Example 1

    Input
    5
    5 1
    3 2
    8 2
    50 3
    100 10
    
    Expected output
    1
    0
    2
    0
    1