ในบทความนี้ เราจะเรียนรู้วิธีสร้างอนุกรมฟีโบนัชชีในภาษา Java อนุกรมฟีโบนัชชีคือลำดับตัวเลขที่ตัวต่อไปได้จากการบวกสองตัวก่อนหน้า
แนวคิดพื้นฐาน
สูตร: Fn = Fn-1 + Fn-2
ค่าเริ่มต้นสามารถเป็น 0, 1 หรือ 1, 1 ก็ได้
ตัวอย่าง: F8 = 0 1 1 2 3 5 8 13 หรือ 1 1 2 3 5 8 13 21
ตัวอย่างการทำงาน
อินพุต:
The input : 15
เอาต์พุต:
The fibonacci series till 15 terms: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร:
my_input,term_1,term_2,term_3 - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ลูป
forวนจาก 1 ถึง N คำนวณผลรวมของสองตัวก่อนหน้าเป็นตัวเลขฟีโบนัชชีปัจจุบัน - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int my_input, term_1 = 0, term_2 = 1, term_3;
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();
System.out.println("The fibonacci series till " + my_input + " terms:");
for (int i = 1; i <= my_input; ++i) {
System.out.print(term_1 + " ");
term_3 = term_1 + term_2;
term_1 = term_2;
term_2 = term_3;
}
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Main {
public static void main(String[] args) {
int my_input = 15, term_1 = 0, term_2 = 1, term_3;
System.out.println("The number are defined as " + my_input);
System.out.println("The fibonacci series till " + my_input + " terms:");
for (int i = 1; i <= my_input; ++i) {
System.out.print(term_1 + " ");
term_3 = term_1 + term_2;
term_1 = term_2;
term_2 = term_3;
}
}
}
ทั้งสองตัวอย่างจะแสดงอนุกรมฟีโบนัชชี 15 ตัว: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377