A. From Hero to Zero
Topic links: http://codeforces.com/contest/1175/problem/A
topic
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
The meaning of problems
Give you two numbers n, k, n you need to go through each one of the following two steps ** ** 0 whereby the output frequency converted:
either n = n-1, either the n = n / k (premise n divisible k).
Thinking
Too large, violent absolute TLE, try is a waste of life!
Clever way:
the n-% k! = 0, the number of steps is the conversion of n% k value, the current case n = (n- minus the number of steps)
n% k == 0, the conversion is a number of steps, the current case n = n / K,
n-0 is completed, the accumulated number of steps can be output.
#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; }