A. From Hero to Zero

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

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→26→25→24→8→7→6→2→1→027→26→25→24→8→7→6→2→1→0.

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

Input

The first line contains one integer tt (1≤t≤1001≤t≤100) — the number of queries.

The only line of each query contains two integers nn and kk (1≤n≤10181≤n≤1018, 2≤k≤10182≤k≤1018).

Output

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

Example

input

Copy

2
59 3
1000000000000000000 10

output

Copy

8
19

Note

Steps for the first test case are: 59→58→57→19→18→6→2→1→059→58→57→19→18→6→2→1→0.

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

 

解题说明:此题是一道数学题,经过最少步数从n变为0,可采用贪心算法,能整除时就整除,否则就减一。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		long long  n, k;
		scanf("%lld%lld", &n, &k);
		long long ans2 = 0;
		while (n >= k)
		{
			ans2 = ans2 + (n%k + 1);
			n = n / k;
		}
		printf("%lld\n", ans2 + n);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值