Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Precision Error in pow function in C++

Правка en1, от 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;
}

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский OrganicBot 2024-09-30 16:33:33 1179 Initial revision (published)