The first type: recursive functions
1 #include <stdio.h> 2 #include <stdlib.h> 3 # Include<assert.h> 4 5 int fabonacci (int n) 6 { 7 if (n<=1&&n>=0) 8 { 9 return n; 10 } 11 return fabonacci (n-1) +Fabonacci (n-2); 12 } 13 int main () 14 { 15 int n; 16 printf ("please input the value of n\n"); 17 &NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d", &n); 18 printf ("the result Of %d is %d\n ", N,fabonacci (n)); 19 return 0; 20 }
The second type: array implementations
Create an array of two elements, initialize to 1, find the value of the nth item, and sequentially find the first two items.
Time complexity: O (N)
Space complexity: O (1)
1 #include <stdio.h> 2 int fib (int n) 3 { 4 int a[2]={1,1}; 5 int i=3; 6 if (n<0) 7 { 8 return -1; 9 } 10 if (n==0) 11 { 12 return 0; 13 } 14 if (n<=2) 15 { 16 Return a[n-1]; 17 } 18 for (; i<=n;i++) 19 { 20 int tmp=a[0]; 21 a[0]=a[1]; 22 a[1]=a[0]+tmp; 23 } 24 &nbsP;return a[1]; 25 } 26 int main () 27 { 28 int n=0; 29 printf ("Please input the value of n\n "); &NBSP;30&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d ", &n); 31 printf ("the num is %d\n", FIB (n)); 32 return 0; 33 } results:please input the value of n0the num is 0[[email Protected] key]$ ./testplease input the value of n5the num is 5[[email protected] key]$ ./testplease input the value of n4the num is 3[[email protected] key]$ ./testplease input the value of n-1the num is -1
The third type: queue implementation
Thinking with the second kind
#include <iostream> #include <queue>using namespace std;int fib (int n) {if (n<0) {return-1;} if (n<=2) {return 1;} Queue<int> Q;q.push (1); Q.push (1); for (int i=2;i<n;i++) {int tmp=q.front (); Q.pop (); Q.push (Tmp+q.front ());} Q.pop (); return Q.front ();} void Test () {int N1 =-1;int n2=2;int n3=5;cout<<fib (N1) <<endl; Cout<<fib (n2) <<endl; Cout<<fib (n3) <<endl;} int main () {test (); System ("pause"); return 0;}
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7F/BC/wKioL1crCJuznWfMAAAdrpDWKjY420.png "title=" ijkfe9p%o%{7en%dnx{@V_B. png "alt=" Wkiol1crcjuznwfmaaadrpdwkjy420.png "/>
The fourth type: Formula implementation
int fib (int n)
{
if (n<0)
{
return-1;
}
Double Gh5=sqrt ((double) 5);
Return (POW ((1+GH5), N)-pow ((1-gh5), N)/(Pow ((double) 2,n) *gh5);
}
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7F/BC/wKioL1crCJuznWfMAAAdrpDWKjY420.png "title=" ijkfe9p%o%{7en%dnx{@V_B. png "alt=" Wkiol1crcjuznwfmaaadrpdwkjy420.png "/>
This article from "Liveyoung" blog, reproduced please contact the author!
The nth item of the Fibonacci sequence.