Find the n-th Fibonacci number (recursive and non-recursive) lease

Fibonacci numbers : also called Fibonacci number;
which refers to a number of columns: 1,1,2,3,5,8,13,21 ...
observe the law found that the Fibonacci numbers 1 It starts from the third start, after the Fibonacci number coefficients are obtained by adding two numbers of the foregoing.
Using the mathematical recursive definition:
F0 = 0;
F1 =. 1;
F2 = F0 + F1 = 0 +. 1 =. 1;
...
Fn = F (n--. 1) + F (n--2)
(n-> = 2 , n belonging to N *) `

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

//递归和非递归分别实现求第n个斐波那契数
//递归
int fab(int n)
{
	if (n <= 2)
		return 1;
	else
		return fab(n - 1) + fab(n - 2);
}

//非递归
int fab(int n)
{
	int a = 1;
	int b = 1;
	int c = 0;
	if (n <= 2)
		return 1;
	else
	{
		while (n > 2)
		{
			c = a + b;
			a = b;
			b = c;
			n--;
		}
	}
	return c;
}



int main()
{
	int n = 0;
	printf("请输入所要求的数字  \n");
	scanf("%d", &n);
	int ret = fab(n);
	printf("%d  ", ret);
	system("pause");
	return 0;
}

Note: The two methods you can choose one
non-recursive method is iterative method!
Popular for recursive method is to constantly put the number of deed and a Fibonacci expressed in the form of a deed that two Fibonacci numbers, and then find the most low-end of the Fibonacci numbers, were constantly backtracking; non-recursive the method is to constantly update two Fibonacci numbers, thus achieving seeking the n-th Fibonacci number.

Published 10 original articles · won praise 16 · views 332

Guess you like

Origin blog.csdn.net/qq_45386840/article/details/102643258