ลำดับฟีโบนักชีเป็นแบบนี้
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,……
ในลำดับนี้ เทอมที่ n คือผลรวมของเทอม (n-1)'th และ (n-2)'th
ในการสร้างเราสามารถใช้วิธีเรียกซ้ำได้ แต่ในการเขียนโปรแกรมแบบไดนามิก ขั้นตอนจะง่ายกว่า มันสามารถเก็บตัวเลขฟีโบนักชีทั้งหมดในตาราง โดยใช้ตารางนั้น มันสามารถสร้างเงื่อนไขถัดไปในลำดับนี้ได้อย่างง่ายดาย
อินพุตและเอาต์พุต
Input: Take the term number as an input. Say it is 10 Output: Enter number of terms: 10 10th fibinacci Terms: 55
อัลกอริทึม
genFiboSeries(n)
ป้อนข้อมูล: จำนวนเงื่อนไขสูงสุด
ผลลัพธ์ − เทอมฟีโบนักชีที่ n
Begin define array named fibo of size n+2 fibo[0] := 0 fibo[1] := 1 for i := 2 to n, do fibo[i] := fibo[i-1] + fibo[i-2] done return fibo[n] End
ตัวอย่าง
#include<iostream>
using namespace std;
int genFibonacci(int n) {
int fibo[n+2]; //array to store fibonacci values
// 0th and 1st number of the series are 0 and 1
fibo[0] = 0;
fibo[1] = 1;
for (int i = 2; i <= n; i++) {
fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous two terms
}
return fibo[n];
}
int main () {
int n;
cout << "Enter number of terms: "; cin >>n;
cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
} ผลลัพธ์
Enter number of terms: 10 10th Fibonacci Terms: 55