ในบทความนี้ เราจะเรียนรู้วิธีหาแฟกทอเรียลของตัวเลขในภาษา Java แฟกทอเรียลคือผลคูณของตัวเลขนั้นกับตัวเลขที่น้อยกว่าลงมาจนถึง 1
ตัวอย่าง
5! = 5 × 4 × 3 × 2 × 1 = 120
ตัวอย่างการทำงาน
อินพุต:
Enter the number: 5
เอาต์พุต:
The factorial of 5 is 120
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร:
my_input, factorial = 1, i - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ลูป
forคูณสะสมตั้งแต่ 1 ถึง my_input - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class FindFactorial {
public static void main(String arg[]) {
int my_input, factorial = 1, 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();
for (i = 1; i <= my_input; i++) {
factorial = factorial * i;
}
System.out.printf("The factorial of %d is %d", my_input, factorial);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class FindFactorial {
public static void main(String arg[]) {
int my_input = 5, factorial = 1, i;
System.out.printf("The number is %d ", my_input);
for (i = 1; i <= my_input; i++) {
factorial = factorial * i;
}
System.out.printf("\nThe factorial of %d is %d", my_input, factorial);
}
}
วิธีทางเลือก: ใช้ Recursion
public static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
ข้อควรระวัง
- แฟกทอเรียลเพิ่มขึ้นเร็วมาก: 13! = 6,227,020,800 (เกิน int ต้องใช้ long)
- 20! = 2,432,902,008,176,640,000 (เกิน long ต้องใช้ BigInteger)
- สำหรับตัวเลขใหญ่ ควรใช้
java.math.BigInteger