斐波那契数列:1,1,2,3,5,8,13,21,34......
前两个数为1,当n>=2时,后面的斐波那契数为前面两个斐波那契数之和。
使用递归的方法求第n个斐波那契数:(具体代码如下)
#include <stdio.h>
#include <stdlib.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 6;
printf("%d \n",fib(n));
system("pause");
return 0;
}
注:递归的写法虽然很好理解,但是函数在调用过程中很多计算都在重复,也比较耗时间。
使用非递归的方法求第n个斐波那契数:(具体代码如下)
#include <stdio.h>
#include <stdlib.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
{
int a = 1;
int b = 1;
int c = 0;
while (n>2)
{
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
}
int main()
{
int n = 6;
printf("%d \n", fib(n));
system("pause");
return 0;
}
注:非递归的形式代码的可读性较差一点,但是比递归形式的写法更加高效。