แฟกทอเรียล (Factorial) คืออะไร?
แฟกทอเรียลของตัวเลข n คือผลคูณของจำนวนเต็มบวกตั้งแต่ 1 ถึง n ใช้สัญลักษณ์ n! เช่น:
0! = 1 1! = 1 2! = 2 × 1 = 2 3! = 3 × 2 × 1 = 6 4! = 4 × 3 × 2 × 1 = 24 5! = 5 × 4 × 3 × 2 × 1 = 120 ... n! = n × (n-1) × (n-2) × ... × 1
ตัวอย่าง
Input: n = 5 Output: 120 Input: n = 6 Output: 720
วิธีการคำนวณ
- ใช้ลูป (Iterative)
- ใช้การเรียกซ้ำ (Recursion)
- ใช้ฟังก์ชัน
อัลกอริทึมแบบ Recursive
- สร้างฟังก์ชัน factorial(n): ถ้า n = 0 คืนค่า 1 มิฉะนั้นคืนค่า n * factorial(n-1)
- ใน main(): กำหนด num = 10 เรียก factorial(num) แล้วแสดงผล
โค้ดภาษา C
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
int num = 10;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}โค้ดภาษา C++
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
int num = 7;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}ผลลัพธ์
C: Factorial of 10 is 3628800 C++: Factorial of 7 is 5040