Fibonacci Numbers: N If N If N F
Fibonacci Numbers: N If N If N F
The Fibonacci numbers fn = f(n) are the numbers characterized by the fact that
every number after the first two is the sum of the two preceding ones. They are defined
with the next recurrent relation:
0, if n 0
f (n) 1, if n 1
f (n 1) f (n 2)
So f0 = 0, f1 = 1, fn = fn-1 + fn-2.
The Fibonacci sequence has the form
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Example. Fill integer array fib with Fibonacci numbers (fib[i] = fi):
#include <stdio.h>
int i, n, fib[47];
int main(void)
{
scanf("%d",&n);
fib[0] = 0; fib[1] = 1;
for(i = 2; i <= n; i++)
fib[i] = fib[i-1] + fib[i-2];
printf("%d\n",fib[n]);
return 0;
}
int fib(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n-1) + fib(n - 2);
}
int main(void)
{
scanf("%d",&n);
printf("%d\n",fib(n));
return 0;
}
Example. Find f(n) – the n-th Fibonacci number with recursion + memorization:
#include <stdio.h>
#include <string.h>
int n, fib[46];
int f(int n)
{
// base case
if (n == 0) return 0;
if (n == 1) return 1;
int main(void)
{
scanf("%d",&n);
printf("%d\n",f(n));
return 0;
}