A

mail@pastecode.io avatar
unknown
c_cpp
14 days ago
827 B
3
Indexable
Never
#include <bits/stdc++.h>
using namespace std;

int log(int n, int k){
    int a = 0;
    while(n>1){
        n /= k;
        a++;
    }
    if(n==1) return a;
    return a-1;
}

int pow(int a, int b){
    if(a==0) return 0;
    if(b==0) return 1;
    int res = 1;
    while(b>0){
        if(b&1) res *= a;
        a *= a;
        b >>= 1;
    }
    return res;
}

int count(int n,int k){
    int c = 0;
    int a;
    while(n>0){
        a = log(n,k);
        n -= pow(k,a);
        c++;
        //cout << n << " " << a << "\n";
    }
    return c;
}

signed main(){
    int t,n,k;
    cin >> t;
    while(t--){
        cin >> n >> k;
        if(k>n || k==1){
            cout << n << "\n";
        }
        else{
            //cout << log(19,3) << "\n";
            cout << count(n,k) << "\n";
        }
    }
    return 0;
}
Leave a Comment