ในบทความนี้ เราจะทำความเข้าใจวิธี หาแฟกทอเรียล (Factorial) ด้วย Recursion
นิยาม: แฟกทอเรียลของ n (เขียนว่า n!) คือผลคูณของจำนวนเต็มบวกจาก 1 ถึง n
สูตร: n! = n × (n-1) × (n-2) × ... × 1 โดยที่ 0! = 1
ตัวอย่าง: 5! = 5 × 4 × 3 × 2 × 1 = 120
ตัวอย่าง Input และ Output
Input:
Enter the number : 7
Output:
The factorial of 7 is 5040
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร int my_input และ long my_result ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น ขั้นตอนที่ 4 - สร้างฟังก์ชัน factorial แบบ recursive รับ int คืน long ขั้นตอนที่ 5 - ถ้า my_input >= 1 คืน my_input * factorial(my_input - 1) มิฉะนั้นคืน 1 ขั้นตอนที่ 6 - เรียกฟังก์ชันและแสดงผล ขั้นตอนที่ 7 - หยุด
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
int my_input;
long my_result;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the number : ");
my_input = my_scanner.nextInt();
my_result = factorial(my_input);
System.out.println("The factorial of " + my_input + " is " + my_result);
}
public static long factorial(int my_input) {
if (my_input >= 1)
return my_input * factorial(my_input - 1);
else
return 1;
}
}
Output
Required packages have been imported A reader object has been defined Enter the number : 7 The factorial of 7 is 5040
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Factorial {
public static void main(String[] args) {
int my_input;
long my_result;
my_input = 7;
System.out.println("The number is defined as " + my_input);
my_result = factorial(my_input);
System.out.println("The factorial of " + my_input + " is " + my_result);
}
public static long factorial(int my_input) {
if (my_input >= 1)
return my_input * factorial(my_input - 1);
else
return 1;
}
}
Output
The number is defined as 7 The factorial of 7 is 5040