Implement Fibonacci sequence in C language

Fibonacci sequence, also known as the "golden section" sequence, such as this sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89... The sequence starts with item 3, and each item is equal to the sum of the previous two items. In C language, we can implement the Fibonacci sequence in many ways. This article focuses on the following three ways to reflect the efficiency of each method: 1) recursive, 2) non-recursive, and 3) array.

1. Recursion. This recursion is multi-branch recursion and will cause stack overflow.

//递归
	#include<stdio.h>

	int Fib(int n)
	{
		if(n==1||n==2)//数列前两项
		{
		return 1;
		 }
		else//从第三项开始
		{
		return Fib(n - 1) + Fib(n - 2);
		}
		return 0;
	}
	int main()
	{
		int n = 0;
		scanf("%d", &n);//输入一个数
		int ret = Fib(n);//计算斐波那契数列
		printf("%d\n", ret);//打印结果
		return 0;
	}

2) Non-recursive. Non-recursion is more efficient than recursion and avoids the time and space of repeated calculations.

//非递归
int main() 
{
	int n = 0;
	printf("请输入一个整数:");
	scanf("%d", &n);
	if (n == 1||n==2) {
		return 1;
	}else {
		int f1 = 1;
		int f2 = 1;
		int f3 = -1;
		for (int i = 3; i <= n; i++) {
			f3 = f1 + f2;
			f1 = f2;
			f2 = f3;
		}
		printf("该整数的Fib数列为%d", f3);
	}

	return 0;
}

3) Array.

	//数组法	
	#include<stdio.h>

	int Fib(int n)
	{
		int i;
		int arr[100] = {0,1,1};
		for (i = 2; i <= n; i++)//从第一项开始
		{
			arr[i] = arr[i - 1] + arr[i - 2];    
		}
		return arr[n];
	}
	int main()
	{
		int n;
		scanf("%d", &n);
		printf("%d", Fib(n));
		return 0;
	}

Guess you like

Origin blog.csdn.net/m0_72000264/article/details/127669666
Recommended