You are viewing a single comment's thread. Return to all comments →
Have you figured out why this happens? I even tried passing a custom function to do the addition and still it overflows!
The problem isn't meant to be solved using long integer. Use integer datatype to solve it. You may divide the bits and then add them seperately.
well i think you are forgetting about kiss
It is a problem that can be solved however you want. But if you look at the hint "When we add several integer values, the resulting sum might exceed the above range. You might need to use long long int in C/C++ or long data type in Java to store such sums. " It would contradict what you said.
Because the type of the accumulator that will be used to determine the sum is based on the type of the third input argument. The literal 0 is not being interpreted as long long int. If you cast the initial value to accumulate appropriately, you get the right answer.
accumulate(arr.begin(),arr.end(),static_cast<long long int>(0))
"The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented."
And Table 6, for literals without suffixes and decimal constants, gives:
long long int
So, without the cast, the literal 0 can be represented as int, so accumulate uses int as the type for accumulation.
I think there is another way , to avoid the static_cast(0) , and do it by simply accumulate(....,0L);
If I remember correct (I am too lazy to search in books or google now to verify!) the L forces the number to be interpreted as long long.
L is the suffix for long just like LL is the suffix for long long. Weird but not confusing. accumulate(....,0LL) avoids the static cast.
or we can do it more simply like this..
accumulate(arr.begin, arr.end(), (long long int)0);
Hi, I understand the 3rd argument of the function accumulate(), which indicates the type of integer literal in this case. But why we need to cast statically as
.....static_cast<long long int>(0))
for the long long integer?
i also don't know that why i cast it explicitly
I am having trouble grasping a clear definition of initial value. What would that mean?
you can check out the below link for video explanation :)