C++ 中的交替斐波那契數


斐波那契數列是指以兩個固定數字開始的數字序列,通常為0、11、1,而序列中的後續元素是序列中前兩個數字的和。

例如,斐波那契數列直到 8 個元素為 0、1、1、2、3、5、8、13、21、34、55、89。

現在,我們來推廣這個數列。其中,第 n 項的值等於第 (n-1) 項和第 (n-2) 項的和。因此,我們來推導一下斐波那契數列中第 n 項的數學公式。

Tn = Tn-1 + Tn-2

使用此公式找出斐波那契數列的第 5 項,我們有了第 3 項和第 4 項。

T5 = T4 + T4

T5 = 3 + 5 = 8。

交替斐波那契數列是一個斐波那契數列,其值與斐波那契數列相同,但數列中需要列印交替的元素。例如,交替斐波那契數列的前 4 個元素為 0、1、3、8。

要建立一個程式來列印交替斐波那契數列,我們將使用該公式並針對數列的每個元素,然後只打印數列的交替值。

演算法

Step 1 : Initialize the first two values of the series n1 = 0 and n2 = 1.
Step 2 : loop from i = 2 to n and follow 3-5 :
Step 3 : next element is n3 = n1 +n2
Step 4 : n1 = n2 and n2 = n3
Step 5 : if i%2 == 0 : print n3

示例

 即時演示

#include <iostream>
using namespace std;
int main(){
   int n1=0,n2=1,n3,i,number;
   cout<<"Enter the number of elements to be present in the series: ";
   cin>>number;
   cout<<"Alternate Fibonacci Series is : ";
   cout<<n1<<" ";
   for (i=2;i<(number*2);++i){
      n3=n1+n2;
      n1=n2;
      n2=n3;
      if(i%2==0)
         cout<<n3<<" ";
   }
   return 0;
}

輸出

Enter the number of elements to be present in the series: 4
Alternate Fibonacci Series is : 0 1 3 8

更新於:2019 年 10 月 16 日

581 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.