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;
}
because it calculates in a way that returns ans in decimals like 10^2 = 99.9999 . And , as you said that you were trying to use this in previous contest, most probably you were assigning this pow(10,x) to an int type variable. So in short the decimal part was cut off and remaining part was stored in ans .
I see.
Thanks for the help.