โปรแกรมหาแฟกทอเรียลโดยใช้การเรียกซ้ำ
โจทย์
Write a Java function that calculates the factorial of a given positive integer using recursion. The factorial of a positive integer , denoted as , is defined as the product of all positive integers less than or equal to . Specifically, is calculated as:
| Input | Output |
|---|---|
| 5 | 120 |
| -3 | Invalid Number! |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Invalid Number!");
} else {
System.out.println(factorial(n));
}
}
public static long factorial(long n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
}หลักการทำงาน
หลักการคำนวณแฟกทอเรียล
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 4! = 4 × 3 × 2 × 1 = 24
- 3! = 3 × 2 × 1 = 6
- 2! = 2 × 1 = 2
- 1! = 1
- 0! = 1 (นิยามพิเศษ)
สูตรทางคณิตศาสตร์
n! = n × (n-1)! เมื่อ n > 1
n! = 1 เมื่อ n = 0 หรือ n = 1คำอธิบาย
การนำเข้าไลบรารี่
import java.util.Scanner; // สำหรับรับข้อมูลจากผู้ใช้1. เมธอด main
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // รับค่าจำนวนเต็ม
if (n < 0) { // ตรวจสอบค่าติดลบ
System.out.println("Invalid Number!");
} else {
System.out.println(factorial(n)); // เรียกใช้เมธอด factorial
}
}2. เมธอด factorial
public static long factorial(long n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}- ใช้ Ternary Operator แทน if-else
- Base Case:
n <= 1return 1 - Recursive Case:
n * factorial(n - 1)
ตัวอย่างการทำงาน
ตัวอย่าง 1: n = 5
การทำงานแบบเรียกซ้ำ:
1. factorial(5)
→ 5 × factorial(4)
→ 5 × 4 × factorial(3)
→ 5 × 4 × 3 × factorial(2)
→ 5 × 4 × 3 × 2 × factorial(1)
→ 5 × 4 × 3 × 2 × 1
= 120
ลำดับการคำนวณย้อนกลับ:
factorial(1) = 1
factorial(2) = 2 × 1 = 2
factorial(3) = 3 × 2 = 6
factorial(4) = 4 × 6 = 24
factorial(5) = 5 × 24 = 120ตัวอย่าง 2: n = -3
Input: -3
Output: Invalid Number!
เนื่องจากแฟกทอเรียลไม่สามารถคำนวณกับจำนวนติดลบได้ปรับปรุงล่าสุด