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.

  • In C++, the accumulate function sums up the elements using the same data type as the elements in the container (in this case, long long), but the initial value you provided, 0, is of type int so the sum also returns as int, as int cannot store large values like 3e12.
  • This mismatch in data types can lead to unexpected results, especially when working with large values.

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