CF1175A.From Hero to Zero

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

From Hero to Zero

You are given an integer nn and an integer kk.

In one step you can do one of the following moves:

  • decrease nn by 11;
  • divide nn by kk if nn is divisible by kk.

For example, if n=27n = 27 and k=3k = 3 you can do the following steps: $27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$.

You are asked to calculate the minimum number of steps to reach 00 from nn.

Input

The first line contains one integer tt (1t1001 \le t \le 100) — the number of queries.

The only line of each query contains two integers nn and kk (1n10181 \le n \le 10^{18}, 2k10182 \le k \le 10^{18}).

Output

For each query print the minimum number of steps to reach 00 from nn in single line.

Note

Steps for the first test case are: $59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$.

In the second test case you have to divide nn by kk 1818 times and then decrease nn by 11.

Samples

2
59 3
1000000000000000000 10
8
19

在线编程 IDE

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