c++intoverflowlong-integerlong-long

Why is "int" not working correctly with "j" but long long is working fine?


This is my code with int j:

void solve(){
    unsigned long long n;
    cin>>n;
    unsigned long long sum = 0;
    int j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }
Input:
499993

Output:
6229295798864

but it is giving wrong output, and here is my code with long long j which is working fine:

void solve(){
    int n;
    cin>>n;
    unsigned long long sum = 0;
    long long j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }
Input:
499993

Output:
41664916690999888

In this case value of j is well below 499993, which is in int range but still, it's not working. Why is it actually happening?

Here is the link to the actual problem. In case, you want to have a look.


Solution

  • Notice that the result of ((4*i)-4)*(j) is an int, since both i and j are int types. The right hand side is promoted to unsigned long long only when adding ((4*i)-4)*(j) to sum. But the expression ((4*i)-4)*(j) already overflows the size of the int type for a large enough n before being promoted.

    However, if you change either of i or j to unsigned long long, the expression ((4*i)-4)*(j) is evaluated to unsigned long long, safely inside the size limits.