ด้วยจำนวน n ภารกิจคือการคำนวณแฟกทอเรียลของตัวเลข แฟกทอเรียลของตัวเลขคำนวณโดยการคูณตัวเลขด้วยค่าจำนวนเต็มที่น้อยที่สุดหรือเท่ากัน
แฟกทอเรียลคำนวณเป็น −
0! = 1 1! = 1 2! = 2X1 = 2 3! = 3X2X1 = 6 4! = 4X3X2X1= 24 5! = 5X4X3X2X1 = 120 . . . N! = n * (n-1) * (n-2) * . . . . . . . . . .*1
ตัวอย่าง
Input 1 -: n=5 Output : 120 Input 2 -: n=6 Output : 720
มีหลายวิธีที่สามารถใช้ได้ -
- ผ่านห่วง
- ผ่านการเรียกซ้ำซึ่งไม่ได้ผลเลย
- ผ่านฟังก์ชัน
ด้านล่างนี้คือการใช้งานโดยใช้ฟังก์ชัน
อัลกอริทึม
Start Step 1 -> Declare function to calculate factorial int factorial(int n) IF n = 0 return 1 End return n * factorial(n - 1) step 2 -> In main() Declare variable as int num = 10 Print factorial(num)) Stop
การใช้ภาษาซี
ตัวอย่าง
#include<stdio.h>
// function to find factorial
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;
} ผลลัพธ์
Factorial of 10 is 3628800
การใช้ C++
ตัวอย่าง
#include<iostream>
using namespace std;
// function to find factorial
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;
} ผลลัพธ์
Factorial of 7 is 5040