Find Minimum Operations

A. Find Minimum Operations

Problem

You are given two integers n n n and k k k.

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

Find the minimum number of operations required to make n n n equal to 0 0 0.

Input

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

The only line of each test case contains two integers n n n and k k k ( 1 ≤ n , k ≤ 1 0 9 1 \le n, k \le 10^9 1n,k109).

Output

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

Example

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

Note

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

  1. Subtract 2 0 = 1 2^0 = 1 20=1 from 5 5 5. The current value of n n n becomes 5 − 1 = 4 5 - 1 = 4 51=4.
  2. Subtract 2 2 = 4 2^2 = 4 22=4 from 4 4 4. The current value of n n n becomes 4 − 4 = 0 4 - 4 = 0 44=0.

It can be shown that there is no way to make n n n equal to 0 0 0 in less than 2 2 2 operations. Thus, 2 2 2 is the answer.

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

  1. Subtract 5 0 = 1 5^0 = 1 50=1 from 3 3 3. The current value of n n n becomes 3 − 1 = 2 3 - 1 = 2 31=2.
  2. Subtract 5 0 = 1 5^0 = 1 50=1 from 2 2 2. The current value of n n n becomes 2 − 1 = 1 2 - 1 = 1 21=1.
  3. Subtract 5 0 = 1 5^0 = 1 50=1 from 1 1 1. The current value of n n n becomes 1 − 1 = 0 1 - 1 = 0 11=0.

It can be shown that there is no way to make n n n equal to 0 0 0 in less than 3 3 3 operations. Thus, 3 3 3 is the answer.

Code

// #include <iostream>
// #include <algorithm>
// #include <cstring>
// #include <stack>//栈
// #include <deque>//队列
// #include <queue>//堆/优先队列
// #include <map>//映射
// #include <unordered_map>//哈希表
// #include <vector>//容器,存数组的数,表数组的长度
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int main()
{
    ll t;
    cin>>t;

    while(t--)
    {
        ll n,k;
        cin>>n>>k;

        if(k==1)
        {
            cout<<n<<endl;
            continue;
        }

        ll ans=0;
        while(n)
        {
            ans+=n%k;
            n/=k;
        }

        cout<<ans<<endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pretty Boy Fox

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值