This page shows some algorithm for calculation of faculty.
The calculation of faculty with a simple loop in an iterative form:
1 | /* |
2 |     factorial_iterative.cpp |
3 |      |
4 |     How to compile with GCC under LINUX/UNIX: |
5 |     g++ -o factorial_iterative factorial_iterative.cpp |
6 | */ |
7 | |
8 | #include <iostream> |
9 | using namespace std; |
10 | |
11 | unsigned long factorial(int num); |
12 | |
13 | int main(int argc, char **argv) { |
14 |     int num; |
15 |      |
16 |     cout << "Calculate factorial number: "; |
17 |     cin >> num; |
18 |      |
19 |     cout << "Result: " << factorial(num) << endl; |
20 |      |
21 |     return 0; |
22 | } |
23 | |
24 | unsigned long factorial(int num) { |
25 |     unsigned long fac = 1; |
26 |      |
27 |     for(int i = num; i >= 2; i--) { |
28 |         fac *= i; |
29 |     } |
30 |      |
31 |     return fac; |
32 | } |
The calculation of faculty in a recursive form:
1 | /* |
2 |     factorial_recursive.cpp |
3 |      |
4 |     How to compile with GCC under LINUX/UNIX: |
5 |     g++ -o factorial_recursive factorial_recursive.cpp |
6 | */ |
7 | |
8 | #include <iostream> |
9 | using namespace std; |
10 | |
11 | unsigned long factorial(int num); |
12 | |
13 | int main(int argc, char **argv) { |
14 |     int num; |
15 |      |
16 |     cout << "Calculate factorial number: "; |
17 |     cin >> num; |
18 |      |
19 |     cout << "Result: " << factorial(num) << endl; |
20 |      |
21 |     return 0; |
22 | } |
23 | |
24 | unsigned long factorial(int num) { |
25 |     if(num < 2) return 1; |
26 |     return num * factorial(num - 1); |
27 | } |
The calculation of faculty with big numbers and with the GMP library:
1 | /* |
2 |     factorial_gmp.cpp |
3 |      |
4 |     GMP library required |
5 |      |
6 |     How to compile with GCC under LINUX/UNIX: |
7 |     g++ -lgmp -lgmpxx -o factorial_gmp factorial_gmp.cpp |
8 | */ |
9 | |
10 | #include <iostream> |
11 | #include <gmpxx.h> |
12 | using namespace std; |
13 | |
14 | mpz_class factorial(int num); |
15 | |
16 | int main(int argc, char **argv) { |
17 |     int num; |
18 |      |
19 |     cout << "Calculate factorial number: "; |
20 |     cin >> num; |
21 |      |
22 |     cout << "Result: " << factorial(num) << endl; |
23 |      |
24 |     return 0; |
25 | } |
26 | |
27 | mpz_class factorial(int num) { |
28 |     if(num < 2) return 1; |
29 |     return num * factorial(num - 1); |
30 | } |