How to calculate factorial of all items in vector with C++

2 Answers

0 votes
#include <iostream>
#include <vector>

int factorial(int n) {
    return (n==1 || n==0) ? 1 : n * factorial(n - 1);
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6};

    for (const auto &item : vec) {
        std::cout << factorial(item) << " ";
    }
    
    return 0;
}



/*
run:

1 2 6 24 120 720 

*/

 



answered May 7, 2021 by avibootz
0 votes
#include <iostream>
#include <vector>

int factorial(int n) {
    int result = 1;
    while (n > 1)
        result *= n--;
    return result;
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6};

    for (const auto &item : vec) {
        std::cout << factorial(item) << " ";
    }
    
    return 0;
}



/*
run:

1 2 6 24 120 720 

*/

 



answered May 7, 2021 by avibootz
...