What is the advantage of typing int until a long time in calculations?

I got the wrong answer using the following function.

vector<int> repeatedNumber(const vector<int> &A) {
    int n = A.size();
    long long linear_sum = 0,square_sum = 0;
    int i = 0;
    for(;i<n;i++){
        linear_sum += A[i];          //LINE 1
        square_sum += A[i]*A[i];     //LINE 2
    }
    linear_sum = linear_sum - (n*(n+1))/2;
    square_sum = square_sum - (n*(n+1)*(2*n+1))/6;
    square_sum /= linear_sum;
    vector<int> ans;
    ans.push_back((linear_sum+square_sum)/2);
    ans.push_back((-linear_sum+square_sum)/2);
    return ans;
}

But when I replaced LINE 1 and LINE 2:

linear_sum += (long long)A[i];          
square_sum += (long long)A[i]*(long long)A[i];     

I got the correct answer. Why just casting an int to a long one solves the problem.

+4
source share
2 answers

When you multiply two values, the intresult is calculated as int.

If the values ​​in the multiplication are too large for int, you get "undefined behavior" (in most conventional hardware you get a seemingly random result).

, 33554432 (.. 1<<25 == 2 25) 32- , 1125899906842624 (.. 2 50) .

long long , , , , .

, , Python Lisp.

, int long long ( , long long , int).

+3

:

A[i]*A[i]

, int long long, .

(long long)A[i]*(long long)A[i];  

, long long

+2

All Articles