# 算法-斐波那契数列

```#include "iostream"
using namespace std;
long long Fibonacci(unsigned int n)
{
if(n <= 0)
return 0;

if(n == 1)
return 1;

return Fibonacci(n - 1) + Fibonacci(n - 2);
}
int main()
{
int sum = Fibonacci(8);
cout<<sum<<endl;
getchar();
return 0;
}```

```#include "iostream"
using namespace std;
long long Fibonacci(unsigned int n)
{
int result[2] = {0, 1};
if(n < 2)
return result[n];

long long  fibNMinusOne = 1;
long long  fibNMinusTwo = 0;
long long  fibN = 0;
for(unsigned int i = 2; i <= n; ++ i)
{
fibN = fibNMinusOne + fibNMinusTwo;

fibNMinusTwo = fibNMinusOne;
fibNMinusOne = fibN;
}

return fibN;
}
int main()
{
long long sum = Fibonacci(8);
cout<<sum<<endl;
getchar();
return 0;
}```

```#include "iostream"
#include <time.h>
using namespace std;
// ====================方法1：递归====================
long long Fibonacci_Solution1(unsigned int n)
{
if(n <= 0)
return 0;

if(n == 1)
return 1;

return Fibonacci_Solution1(n - 1) + Fibonacci_Solution1(n - 2);
}

// ====================方法2：循环====================
long long Fibonacci_Solution2(unsigned n)
{
int result[2] = {0, 1};
if(n < 2)
return result[n];

long long  fibNMinusOne = 1;
long long  fibNMinusTwo = 0;
long long  fibN = 0;
for(unsigned int i = 2; i <= n; ++ i)
{
fibN = fibNMinusOne + fibNMinusTwo;

fibNMinusTwo = fibNMinusOne;
fibNMinusOne = fibN;
}

return fibN;
}
int main()
{
clock_t start1,finish1,start2,finish2;
double totaltime1,totaltime2;
start1=clock();
long long sum1 = Fibonacci_Solution1(40);
finish1=clock();
totaltime1=(double)(finish1-start1)/CLOCKS_PER_SEC;
cout<<"结果："<<sum1<<endl<<"时间："<<totaltime1<<endl;

start2=clock();
long long sum2 = Fibonacci_Solution2(40);
finish2=clock();
totaltime2=(double)(finish2-start2)/CLOCKS_PER_SEC;
cout<<"结果："<<sum2<<endl<<"时间："<<totaltime2<<endl;

getchar();
return 0;
}```

f(7)问题：

f(6)问题：

96 篇文章35 人订阅

0 条评论

## 相关文章

### CDOJ 1330 柱爷与远古法阵【高斯消元，卡精度】

2577

Jungle Roads Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768...

2957

### java之内部类

1 public class RedCowForm { 2 static String formName ; 3 RedCow cow ;...

2674

1569

621

862

772

### UVA10129：Play on Words（欧拉回路）

Some of the secret doors contain a very interesting word puzzle. The team of arc...

801

### HDU 3018 Ant Trip（欧拉回路）

#include <bits/stdc++.h> using namespace std; const int N=100005; int f[N]; ...

662

1898