Computer >> Máy Tính >  >> Lập trình >> Lập trình

Tạo chuỗi Fibonacci


Dãy Fibonacci giống như thế này,

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,……

Trong dãy số này, số hạng thứ n là tổng các số hạng thứ (n-1) 'và (n-2)'.

Để tạo ra, chúng ta có thể sử dụng phương pháp đệ quy, nhưng trong lập trình động, thủ tục đơn giản hơn. Nó có thể lưu trữ tất cả các số Fibonacci trong một bảng, bằng cách sử dụng bảng đó, nó có thể dễ dàng tạo ra các số hạng tiếp theo trong chuỗi này.

Đầu vào và Đầu ra

Input:
Take the term number as an input. Say it is 10
Output:
Enter number of terms: 10
10th fibinacci Terms: 55

Thuật toán

genFiboSeries(n)

Đầu vào: số lượng điều khoản tối đa.

Đầu ra - Thuật ngữ Fibonacci thứ 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

Ví dụ

#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;
}

Đầu ra

Enter number of terms: 10
10th Fibonacci Terms: 55