微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Educational Codeforces Round 66 (Rated for Div. 2) A

A. From Hero to Zero

题目链接http://codeforces.com/contest/1175/problem/A

题目

ou are given an integer n and an integer k
In one step you can do one of the following moves:
decrease n by 1;
divide n by k if n is divisible by k.
For example,if n=27 and k=3 you can do the following steps: 27→26→25→24→8→7→6→2→1→0.
You are asked to calculate the minimum number of steps to reach 0 from n.

input

The first line contains one integer t (1≤t≤100) — the number of queries.
The only line of each query contains two integers n
and k (1≤n≤1018,2≤k≤1018).

output

For each query print the minimum number of steps to reach 0
from n in single line

Example

intput

2
59 3
1000000000000000000 10


output

8

19

题意

给你两个数n,k,你需要将n每次经过以下两个**步骤之一**从而得到0,输出变换次数
要么n=n-1,要么将n=n/k(前提n能整除k)。

思路

范围太大,暴力绝对TLE,尝试就是浪费生命!
巧办法:
n%k!=0时,变换的步数就是n%k的值,此时当前n=(n-减掉该步数)
n%k==0时,变换的步数就是1,此时当前n=n/k,
n为0结束,将步数累加输出即可。

 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e5+7;
int main()
{
    int T;
    cin>>T;
    while(T--) {
        ll n,k;
        cin >> n >> k;
        ll result = 0;
        while (n != 0) {
            ll book = n % k;
            if (book != 0) {
                result += book;
                n = n - book;
            } else {
                result += 1;
                n = n / k;
            }
        }
        cout << result << endl;
    }
return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。