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:

C++




#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



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:

  • startRange: specifies the position in the series from which we want the operation to start
  • end-range: specifies the position in the series up to which we want to perform the specific operation
  • initialValue: the initial value is given to the accumulate() function, it stores the result of the operation in initialValue.

Similar Reads

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:...

Why this problem occurs?

...

Solution to this issue:

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