When adding a large number to a large result obtained by power function in c++, the final answer is somehow getting incremented or decremented by 1.
#include "bits/stdc++.h"
using namespace std;
#define dbg(x) cout<<#x<<" = "<<x<<ln
unsigned long long bla = pow(10, 16-1) + 8999999999999997;
dbg(bla);
unsigned long long blb = pow(10, 16-1) + 8111111111111111;
dbg(blb);
The output for the above code is:
bla = 9999999999999996
blb = 9111111111111112
You can see that the result has swayed by 1 in each case.
However this problem disappears and I get the correct result when I split the operation into 2 lines as shown in the code below:
unsigned long long bla = pow(10, 16-1);
bla += 8999999999999997;
dbg(bla);
I believe this phenomenon is caused because the numbers are approaching the 64 bit length which is causing some issues in addition but I would greatly appreciate some clarity about why this is actually happening.