How to get the factorial of a number using std :: accumulate()?

86 Views Asked by At

Hello! I was using the function std::accumulate() to see whether it would return the factorial of 10 on applying a multiplication operation on a sequence of the natural numbers from 1 to 10, as follows:

#include <iostream>
#include <numeric>
#include <functional>
using namespace std;

int main()
{
    int numbers[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    cout << "The factorial of 10 is " << accumulate(numbers + 1, numbers + 11,   multiplies<int>()) << "\n";"
}

Now I have gotten weird errors that say that the function std::accumulate() is not a valid operand and else (I do not remember the errors).

and as I was writing this question I tried running the code again and suddenly, the errors disappeared and all went well?

Can someone explain this weird behavior?

1

There are 1 best solutions below

0
Toby Speight On BEST ANSWER

You missed the initial-value argument (the third argument of std::accumulate):

#include <array>
#include <iostream>
#include <numeric>

int main()
{
    auto numbers = std::array{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::cout << "The factorial of 10 is "
              << accumulate(numbers.begin(), numbers.end(),  1,  std::multiplies<int>{})
        //                                                  
              << '\n';
}

Note that int is a poor choice of arithmetic type for this computation, as the result will be larger than 32767, which is all that INT_MAX is guaranteed to be. Signed integer overflow is Undefined Behaviour, so should be avoided at all costs.