Recursive algorithm 2-simple recursive Fibonacci sequence (recursive method)

The Fibonacci sequence refers to such a sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21,... Starting from the third number, each number is the sum of the first two numbers. Write an algorithm to output the first n terms of the Fibonacci sequence.

[Analysis] The
Fibonacci sequence can be written as the following formula:

fibibacci(n)= \begin{cases} 0 & n=0 \\ 1 & n=1 \\ fibibacci(n-1) + fibibacci(n-2) & n=2,3,4,... \end{cases}

When n=4, the process of finding the value of fibibacci(4) is shown in the figure below.

Among them, the shaded part in the figure is the corresponding function value. To find the value of fibibacci(4), you need to know the values ​​of fibibacci(3) and fibibacci(2), and to find the value of fibibacci(3) you need to know the values ​​of fibibacci(2) and fibibacci(1), and find the value of fibibacci(2) The value needs to know the value of fibibacci(1) and fibibacci(0). fibibacci(1)=1, fibibacci(0)=0, so return directly.

code:

#include<stdio.h>
#include <iostream>
int fib(int n);
void main()
{
	int n;
	printf("请输入项数:");
	scanf("%d", &n);
	printf("第%d项的值:%d\n", n, fib(n));
	system("pause");
}
int fib(int n)
{
	if (n == 0)
		return 0;
	if (n == 1)
		return 1;
	if (n > 1)
		return fib(n - 1) + fib(n - 2);
	
}

result:

 

Guess you like

Origin blog.csdn.net/baidu_36669549/article/details/104133121