Open In App

Gfact | Why accumulate function in C++ gives wrong answer for large numbers?

The C++ accumulate() function calculates the sum of numerical values under a certain range. It can also be used to effectively iterate and compute the sum of an entire array or a vector with ease.



Syntax of C++ accumulate() function:

accumulate(startRange, endRange, initialValue);

Parameters of C++ accumulate() function:

Why accumulate function in C++ gives wrong answer for large numbers?

The reasons why the accumulate function may give wrong answers for large numbers include:



To work with large numbers without encountering these issues, it’s crucial to choose appropriate data types, ensure consistency in data types, and be mindful of integer overflow and precision concerns.

Code to predict output:




#include <bits/stdc++.h>
using namespace std;
 
// Drivers code
int main()
{
    long long val = 1000000000000;
    vector<long long> v({ val, val, val });
 
    // Now take sum of all elements
    long long sum = accumulate(v.begin(), v.end(), 0);
    cout << sum << '\n';
    return 0;
}

Expected Output: 3000000000000


Actual Output : 2112827392


Why this problem occurs?

The issue in your code is due to integer overflow. If the sum of the numbers being accumulated exceeds the maximum value representable by the data type (e.g., int or long long), overflow occurs, and the result becomes incorrect.

Solution to this issue:

To fix this issue, you should ensure that the initial value provided to accumulate is of the same data type as the elements in the vector (long long in this case).

Here’s the modified code:




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    long long val = 1e12;
    vector<long long> v({ val, val, val });
    // now take sum of all elements
    long long sum
        = accumulate(v.begin(), v.end(), (long long)0);
    cout << sum << '\n';
    return 0;
}

Output
3000000000000


Article Tags :