Fibonacci sequence: 1 1 2 3 5 8 13...
Starting from the third number, each number is equal to the sum of the first two numbers.
Enter a number to indicate which Fibonacci number is
1. Recursion (when the number of inputs is too large, the efficiency is too slow)
#define _CRT_SECURE_NO_WARNINGS 1
#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;
scanf("%d", &n);
int ret = Fib(n);
printf("%d\n", ret);
return 0;
}
2. Non-recursive (iterative)
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int Fib(int m)
{
int a = 1;
int b = 1;
int c = 1;
while (m > 2)
{
c = a + b;
a = b;
b = c;
m--;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d\n", ret);
return 0;
}