Fibonacci
Fibonacci
Fibonacci
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;
}
i 0 1 2 3 4 5 6 7 8 9 10 ...
fib[i] 0 1 1 2 3 5 8 13 21 34 55 ...
int n;
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;
}
f(5)
f(4) + f(3)
f(1) + f(0)
Example. Find f(n) – the n-th Fibonacci number with recursion + memoization:
#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;
printf("%d\n",f(n));
return 0;
}
f(5)
f(4) + f(3)
mem
f(3) + f(2)
mem
f(2) + f(1)
f(1) + f(0)
E-OLYMP 8295. Fibonacci string generation Generate the n-th Fibonacci string
that is defined with the next recurrent formula:
• f(0) = "a";
• f(1) = "b";
• f(n) = f(n – 1) + f(n – 2), where "+" operation means concatenation
For example, f(3) = f(2) + f(1) = (f(1) + f(0)) + f(1) = "b" + "a" + "b" = "bab".
► Implement a recursive function that generates the n-th Fibonacci string.
string f(int n)
{
if (n == 0) return "a";
if (n == 1) return "b";
return f(n-1) + f(n-2);
}