My code gives different results on different compilers, the following code gives 499999998352516354 when I enter 1,1000000000 as my input on vs code which is the desired results while it gives 499999998352516352 on codeforces
#include <bits/stdc++.h>
using namespace std;
int main()
{
cout<<fixed<<setprecision(90);
long long x,y;
long long sum=0;
long long z=1;
cin>>x;
for (int i = 0; i < x; i++)
{
cin>>y;
sum=y*(y+1)/2;
z= log2(y);
sum-=2*(pow(2,1+z)-1);
cout<<sum<<"\n";
sum=0;
}
}
>Solution :
Use std::llround() function around pow() and your code will work.
It is because pow() gives floating value which can be incorrectly truncated to 1 less than needed. And llround() gives correct rounding to whole integer.
Below is fixed code, I also adjusted code formatting and changed to correct necessary C++ headers.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
cout << fixed << setprecision(90);
long long x, y;
long long sum = 0;
long long z = 1;
cin >> x;
for (int i = 0; i < x; i++) {
cin >> y;
sum = y * (y + 1) / 2;
z = log2(y);
sum -= 2 * (llround(pow(2, 1 + z)) - 1);
cout << sum << "\n";
sum = 0;
}
}
Input:
1 1000000000
Output:
499999998352516354
As it is suggested in comments you may also use bit shifting 1LL << x instead of pow(2, x) if x is non-negative integer.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
cout << fixed << setprecision(90);
long long x, y;
long long sum = 0;
long long z = 1;
cin >> x;
for (int i = 0; i < x; i++) {
cin >> y;
sum = y * (y + 1) / 2;
z = log2(y);
sum -= 2 * ((1LL << (1 + z)) - 1);
cout << sum << "\n";
sum = 0;
}
}
As @Bathsheba suggests in comments it is also needed to consider z = log2(y); line. Better to use z = llround(log2(y + 1e-5) - 0.5);, here 1e-5 is a small epsilon value that should be added. I re-checked, this new expression gives exactly same result.