แฟกทอเรียลของจำนวนเต็มบวก 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