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.
Try it online!
#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. And instead log2(y)
if y
is integer then one can use std::bit_width(y) - 1
(read about std::bit_width)
Try it online!
#include <iostream>
#include <iomanip>
#include <cmath>
#include <bit>
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 = std::bit_width<unsigned long long>(y) - 1;
sum -= 2 * ((1LL << (1 + z)) - 1);
cout << sum << "\n";
sum = 0;
}
}