Precision Error in pow function in C++

Revision en1, by OrganicBot, 2024-09-30 16:33:33

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;
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English OrganicBot 2024-09-30 16:33:33 1179 Initial revision (published)