问题描述:
斐波那契数列,又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。 现在我们要求数列的第n项。
二分递归版:
// Fibonacci数 (二分递归版)
#include <stdio.h>
int fib(int n)
{
return (2 > n) ? n : fib(n-1)+fib(n-2);
}
int main()
{
printf("%d\n",fib(8)); //1 1 2 3 5 8 13 21
return 0;
}
运行结果:
21
--------------------------------
Process exited with return value 0
Press any key to continue . . .
迭代版:
这里巧妙的应用了将数列构造一项 fib(0) = 0.
// Fibonacci数(迭代版)
#include <stdio.h>
int fib(int n)
{
int f0 = 0, f1 = 1; //初始化fib(0) = 0,fib(1) = 1
while (0 < n--)
{
f1 += f0;
f0 = f1 - f0;
}
return f1;
}
int main()
{
printf("%d\n",fib(5)); // 1 1 2 3 5
return 0;
}
运行结果:
8
--------------------------------
Process exited with return value 0
Press any key to continue . . .