CF2020A.Find Minimum Operations

传统题 时间 2000 ms 内存 256 MiB 3 尝试 1 已通过 1 标签

Find Minimum Operations

You are given two integers nn and kk.

In one operation, you can subtract any power of kk from nn. Formally, in one operation, you can replace nn by (nkx)(n-k^x) for any non-negative integer xx.

Find the minimum number of operations required to make nn equal to 00.

Input

Each test contains multiple test cases. The first line contains the number of test cases tt (1t1041 \le t \le 10^4). The description of the test cases follows.

The only line of each test case contains two integers nn and kk (1n,k1091 \le n, k \le 10^9).

Output

For each test case, output the minimum number of operations on a new line.

Note

In the first test case, n=5n = 5 and k=2k = 2. We can perform the following sequence of operations:

  1. Subtract 20=12^0 = 1 from 55. The current value of nn becomes 51=45 - 1 = 4.
  2. Subtract 22=42^2 = 4 from 44. The current value of nn becomes 44=04 - 4 = 0.

It can be shown that there is no way to make nn equal to 00 in less than 22 operations. Thus, 22 is the answer.

In the second test case, n=3n = 3 and k=5k = 5. We can perform the following sequence of operations:

  1. Subtract 50=15^0 = 1 from 33. The current value of nn becomes 31=23 - 1 = 2.
  2. Subtract 50=15^0 = 1 from 22. The current value of nn becomes 21=12 - 1 = 1.
  3. Subtract 50=15^0 = 1 from 11. The current value of nn becomes 11=01 - 1 = 0.

It can be shown that there is no way to make nn equal to 00 in less than 33 operations. Thus, 33 is the answer.

Samples

6
5 2
3 5
16 4
100 3
6492 10
10 1
2
3
1
4
21
10

在线编程 IDE

建议全屏模式获得最佳体验