C++ Program to Find Factorial of a Number using Dynamic Programming

This C++ Program demonstrates the the computation of Factorial of a number using Dynamic Programming .

Here is source code of the C++ Program to Find Factorial of a Number using Dynamic Programming . The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `/* `
2. ` * C++ Program to Find Factorial of a Number using Dynamic Programming `
3. ` */`
4. `#include <cstring>`
5. `#include <iostream>`
6. `#include <cstdlib>`
7. `#define ll long long`
8. `using namespace std;`
9. ` `
10. `int result[1000] = {0};`
11. `/* `
12. ` * Find Factorial of a Number using Dynamic Programming `
13. ` */`
14. `ll fact_dp(int n)`
15. `{`
16. `    if (n >= 0) `
17. `    {`
18. `        result[0] = 1;`
19. `        for (int i = 1; i <= n; ++i) `
20. `        {`
21. `            result[i] = i * result[i - 1];`
22. `        }`
23. `        return result[n];`
24. `    }`
25. `}`
26. `/* `
27. ` * Main`
28. ` */`
29. `int main()`
30. `{`
31. `    int n;`
32. `    while (1)`
33. `    {`
34. `        cout<<"Enter interger to compute factorial(0 to exit): ";`
35. `        cin>>n;`
36. `        if (n == 0)`
37. `            break;`
38. `        cout<<fact_dp(n)<<endl;`
39. `    }`
40. `    return 0;`
41. `}`

```\$ g++ fact_dp.cpp
\$ a.out

Enter interger to compute factorial(0 to exit): 10
3628800
Enter interger to compute factorial(0 to exit): 20
2432902008176640000
Enter interger to compute factorial(0 to exit): 15
1307674368000
Enter interger to compute factorial(0 to exit): 0

------------------
(program exited with code: 1)

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.