ในบทความนี้ เราจะมาทำความเข้าใจวิธีหาแฟกทอเรียลของตัวเลขกัน แฟกทอเรียลของตัวเลขเป็นผลคูณของตัวมันเองกับจำนวนที่ต่ำกว่าแต่ละตัว
แฟกทอเรียลเป็นฟังก์ชันที่ใช้กับจำนวนธรรมชาติที่มากกว่าศูนย์ สัญลักษณ์ของฟังก์ชันแฟกทอเรียลคือเครื่องหมายอัศเจรีย์หลังตัวเลข เช่น 5!
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Enter the number : 5
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็นเช่น 5! =5x4x3x2x1
The factorial of 5 is 120
อัลกอริทึม
Step1- Start Step 2- Declare three integers: my_input_1, factorial and i Step 3- Prompt the user to enter an integer value/ Hardcode the integer Step 4- Read the values Step 5- Run while loop, multiply the number with its lower number and run the loop till the number is reduced to 1. Step 6- Display the result Step 7- Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
import java.util.Scanner;
public class FindFactorial{
public static void main(String arg[]){
int my_input, factorial, i;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.println("Enter a number: ");
my_input = my_scanner.nextInt();
factorial=1;
for(i=1;i<=my_input;i++){
factorial=factorial*i;
}
System.out.printf("The factoral of %d is %d" , my_input,factorial);
}
} ผลลัพธ์
Required packages have been imported A scanner object has been defined Enter a number: 5 The factorial of 5 is 120
ตัวอย่างที่ 2
ในที่นี้ ได้มีการกำหนดจำนวนเต็มไว้แล้ว และค่าของมันถูกเข้าถึงและแสดงบนคอนโซล
public class FindFactorial{
public static void main(String arg[]){
int my_input, factorial, i;
my_input = 5;
System.out.printf("The number is %d ",my_input );
factorial=1;
for(i=1;i<=my_input;i++){
factorial=factorial*i;
}
System.out.printf("\nThe factorial of %d is %d" , my_input,factorial);
}
} ผลลัพธ์
The number is 5 The factorial of 5 is 120