裴波那契数列

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <exception>
 4 #include <stack>
 5 using namespace std;
 6 
 7 /*
 8 裴波那契数列
 9 写一个函数:输入n,求裴波那契(Fibonacci)数列的第n项.
10 裴波那契数列的定义如下:
11          0   n=0
12  f(n) =  1   n=1
13          f(n-1)+f(n-2) n>1;
14 
15 题目二:一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法.
16 */
17 int Fibonaccire(unsigned int n)
18 {
19     if (n==0) return 0;
20     if (n==1) return 1;
21     else return Fibonaccire(n-1) + Fibonaccire(n-2);
22 }
23 
24 int Fibonacci(unsigned int n)
25 {
26     if(n==0) return 0;
27     if(n==1) return 1;
28     int left = 0;
29     int right = 1;
30     for(int i = 2;i<=n;++i)
31     {
32         int temp = left;
33         left = right;
34         right = temp + right;
35     }
36     return right;
37 }
38 
39 int _tmain(int argc, _TCHAR* argv[])
40 { 
41     cout<<Fibonaccire(9)<<endl;
42     cout<<Fibonacci(9)<<endl;
43     return 0 ;
44 }

 

posted @ 2014-02-21 00:13  CrazyCode.  阅读(576)  评论(0)    收藏  举报