OrganicBot's blog

By OrganicBot, history, 3 months ago, In English

Hey Everyone, I am writing this to ask for help in understanding where the precision errors in the pow function arise during calculations.

In last div 2, while trying question A, I encountered :

here, x is the greatest power of k less than n. why did it suddenly subtract an extra one when x is clearly 1000. Here is the code for reference:

#include <bits/stdc++.h>
#define el "\n"
#define ll long long
#define OrganicBot ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr)

using namespace std;

void solve() {
    ll n,k;
    cin >> n >> k;

    ll ans = 0;
    ll x = 0;
    cout <<"n: "<< n << el;
    while(n>=k){
        x = floor(log(n)/log(k));
        cout << "x: " << pow(k,x) << el;
        n-=pow(k,x);
        cout <<"n: "<< n << el;
        ans++;
    }
    
    //ans++;
    if(n<k){
        ans += k-n;
    }
    cout << ans << el;
}

int main() {
    OrganicBot;
    int t_cases;
    cin >> t_cases;
    while (t_cases--) {
        solve();
    }
    return 0;
}

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it