#include<stdio.h>
int Fib(int x)
{
if (x <= 2)
{
return 1;
}
else
{
return Fib(x - 1) + Fib(x - 2);
}
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d", ret);
return 0;
}
本代码可以实现求第n个斐波那契数,但代码效率比较低,当n较大是计算时间较长.当求50的斐波那契数时:本代码实现过程如下:求50就要求49和48,然而49又要求48和47 如此反复.
50
49 48
48 47 47 46
47 46 46 45 46 45 45 44
......
代码运算量过大.
#include<stdio.h>
int count = 0;
int Fib(int x)
{
if (x == 3)
{
count++;//计算3出现的次数
}
if (x <= 2)
{
return 1;
}
else
{
return Fib(x - 1) + Fib(x - 2);
}
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d", ret);
printf("%d", count);
return 0;
}
30
832040317811
可见运算量之大.
对代码进行改进;
int Fib(int x)
{
int a = 1;
int b = 1;
int c = 1;
while (x > 2)
{
c = a + b;
a = b;
b = c;
x--;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d", ret);
return 0;
}