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)
Press return to continue

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

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.