C++斐波納契數列

C++中的斐波納契係數實現:在斐波納契系列的情況下,下一個數字是前兩個數字的總和,例如:0,1,1,2,3,5,8,13,21等。斐波那契數列的前兩個數字是:01

有兩種方法來寫斐波那契數列程序:

  • 不使用遞歸實現斐波那契數列
  • 使用遞歸實現斐波那契數列

不使用遞歸實現斐波那契數列

下面來看看看不使用遞歸在C++中實現斐波那契數列(fibonacci)程序。

#include <iostream>  
using namespace std;  
int main() {  
    int n1=0,n2=1,n3,i,number;    
    cout<<"Enter the number of elements: ";    
    cin>>number;    
    cout<<n1<<" "<<n2<<" "; //printing 0 and 1  
    //loop starts from 2 because 0 and 1 are already printed    
    for(i=2;i<number;++i) 
    {    
        n3=n1+n2;    
        cout<<n3<<" ";    
        n1=n2;    
        n2=n3;    
    }    
    return 0;  
}

執行上面代碼,得到以下結果 -

Enter the number of elements: 10
0 1 1 2 3 5 8 13 21 34

在C++中使用遞歸實現斐波那契數列

下面來看看看使用遞歸在C++中的斐波那契(fibonacci)數列程序。

#include<iostream>    
using namespace std;      
void printFibonacci(int n){    
    static int n1=0, n2=1, n3;    
    if(n>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         cout<<n3<<" ";    
         printFibonacci(n-1);    
    }    
}    
int main(){    
    int n;    
    cout<<"Enter the number of elements: ";    
    cin>>n;    
    cout<<"Fibonacci Series: ";    
    cout<<"0 "<<"1 ";  
    printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
     return 0;  
}

執行上面代碼得到以下結果 -

Enter the number of elements: 15 
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377