使用动态规划算法用 C++ 程序求一个数字的阶乘
正整数 n 的阶乘等于 1*2*3*...n。负数没有阶乘。这里提供了一个 C++ 程序,用动态规划算法计算给定输入的阶乘。
算法
Begin fact(int n): Read the number n Initialize i = 1, result[1000] = {0} result[0] = 1 for i = 1 to n result[i] = I * result[i-1] Print result End
示例代码
#include <iostream> using namespace std; int result[1000] = {0}; int fact(int n) { if (n >= 0) { result[0] = 1; for (int i = 1; i <= n; ++i) { result[i] = i * result[i - 1]; } return result[n]; } } int main() { int n; while (1) { cout<<"Enter integer to compute factorial (enter 0 to exit): "; cin>>n; if (n == 0) break; cout<<fact(n)<<endl; } return 0; }
输出
Enter integer to compute factorial (enter 0 to exit): 2 2 Enter integer to compute factorial (enter 0 to exit): 6 720 Enter integer to compute factorial (enter 0 to exit): 7 5040 Enter integer to compute factorial (enter 0 to exit): 10 3628800 Enter integer to compute factorial (enter 0 to exit): 0
广告