Fibonacci sequence [C language implementation]

1. Definition:

The Fibonacci sequence, also known as the golden section sequence , was introduced by the mathematician Leonardo Fibonacci with the example of rabbit breeding, so it is also called the "rabbit sequence" . It is such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... This sequence starts from the third item, and each item is equal to the sum of the previous two items .

2. The method of finding the nth Fibonacci number:

(1) recursion

#include<stdio.h>
int Fib(int n)
{
	if (n <= 2)
	{
		return 1;
	}
	else
	{
		return Fib(n - 1) + Fib(n - 2);
	}
}
int main()
{
	int n = 0;
	printf("input n: ");
	scanf("%d", &n);
	printf("%d\n",Fib(n));

	return 0;
}

Let's enter 50 to see what the 50th Fibonacci number is

It can be seen that the cursor keeps flashing, indicating that the program is always executing, but there is no output result. Why is this?

 It can be seen that there are many numbers of repeated calculations, which is not a small amount of work. We can calculate the number of times a certain Fibonacci number is repeatedly calculated.

Count the number of times the third Fibonacci number is repeatedly calculated when calculating the 40th Fibonacci number (the code is as follows):

//递归法
#include<stdio.h>
int count = 0;//全局变量

int Fib(int n)
{
	//统计的是 第3个斐波那契数被重复计算的次数
	if (3 == n)
	{
		count++;
	}
	if (n <= 2)
	{
		return 1;
	}
	else
	{
		return Fib(n - 1) + Fib(n - 2);
	}
}
int main()
{
	int n = 0;
	printf("input n: ");
	scanf("%d", &n);
	printf("%d\n",Fib(n));
	printf("count= %d\n", count);

	return 0;
}

 It can be seen that the calculation of the computer is very large, the time complexity and space complexity are extremely high, and it is easy to cause stack overflow and timeout. So using recursion here is obviously not a wise choice.

(2) iteration

//迭代法
#include<stdio.h>
int Fib(int n)
{
	int a = 1;
	int b = 1;
	int c = 1;
	while (n>2)
	{
		c = a + b;
		a = b;
		b = c;
		n--;
	}
		return c;
}
int main()
{
	int n = 0;
	printf("input n: ");
	scanf("%d", &n);
	printf("%d\n",Fib(n));

	return 0;
}

The efficiency of the loop iteration method is much higher than that of recursion, but the readability of the recursive code is slightly worse.

3. Tips:

(1) Many problems are explained in a recursive form simply because they are clearer than a non-recursive form.

(2) But the iterative implementation of these problems is often more efficient than the recursive implementation, although the code is slightly less readable.

(3) When a problem is quite complex and difficult to implement iteratively, the simplicity of recursive implementation can compensate for the runtime overhead it brings.

Guess you like

Origin blog.csdn.net/weixin_74937672/article/details/128725865