#include <stdio.h>
unsigned int Loop_Fibonacci(unsigned int n);
unsigned int Recu_Fibonacci(unsigned int n);
int main()
{
//给定正整数n(项数),返回响应的斐波那契数值
//斐波那契额数列(1、1、2、3、5、8、13...)
int n = 30;
printf("循环实现:%u\n", Loop_Fibonacci(n) );
printf("递归实现:%u\n", Recu_Fibonacci(n) );
return 0;
}
//循环实现
/*
n1 = 1
n2 = 1
n3 = n1 + n2 = 2
n1 = n2 1
n2 = n3 2
n3 = n1 + n2 = 3
n1 = n2 = 2
n2 = n3 = 3
n3 = n1 + n2
*/
unsigned int Loop_Fibonacci(unsigned int n)
{
int a1 = 1;
int a2 = 1;
if( n <= 2 )
{
return 1;
}else{
int n1 = a1;
int n2 = a2;
int n3 = n1 + n2;
for (int i = 4; i <= n; ++i)
{
n1 = n2;
n2 = n3;
n3 = n1 + n2;
//printf("%d\n", n3);
}
return n3;
}
}
//递归实现
/*
1
1
2
3
5
8
13
*/
unsigned int Recu_Fibonacci(unsigned int n)
{
return n<=2 ? 1 : Recu_Fibonacci(n -1) + Recu_Fibonacci(n -2);
}