Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My code gives different results on different compilers

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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 * ((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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading