How is it possible to get given output with code below ??
#include <iostream>
#include <vector>
#include <future>
#include <algorithm>
#include <cmath>
using namespace std;
void solve() {
int n = 1000000000;
long long ans = n;
ans = (ans * (ans + 1)) / 2;
long i{0};
while(true) {
const auto num = pow(2, i++);
if(num > n) {
break;
}
cout << ans << " - " << (2 * num);
ans -= 2 * num;
cout << " = "<< ans << endl;
if(i > 10){
break;
}
}
}
int main() {
solve();
return 0;
}
Getting the output as:
500000000500000000 - 2 = 500000000500000000
500000000500000000 - 4 = 500000000500000000
500000000500000000 - 8 = 500000000500000000
500000000500000000 - 16 = 500000000500000000
500000000500000000 - 32 = 500000000500000000
500000000500000000 - 64 = 500000000499999936
500000000499999936 - 128 = 500000000499999808
500000000499999808 - 256 = 500000000499999552
500000000499999552 - 512 = 500000000499999040
500000000499999040 - 1024 = 500000000499998016
500000000499998016 - 2048 = 500000000499995968
I tried to subtract the required value from ans using the logic below
int d = 1;
while(d <= n) {
cout << res << " - " << d << endl;
res -= 2 * d;
d *= 2;
}
Where res have same value as ans in code snipped above, where am I lacking?? Please help