Fibonacci numbers
The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa,
known as Fibonacci:
https://en.wikipedia.org/wiki/Fibonacci_number
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;
}
The biggest Fibonacci number that fits into int type is
f46 = 1836311903
The biggest Fibonacci number that fits into long long type is
f92 = 7540113804746346429
If you want to find Fibonacci number fn for n > 92, use BigInteger type.
Example. Find f(n) – the n-th Fibonacci number with recursion:
#include <stdio.h>
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;
}
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;
// if the value fib[n] is ALREADY found, just return it
if (fib[n] != -1) return fib[n];
// if the value fib[n] is not found, calculate and memorize it
return fib[n] = f(n-1) + f(n - 2);
}
int main(void)
{
scanf("%d",&n);
// fib[i] = -1 means that this value is not calculated yet
memset(fib,-1,sizeof(fib));
printf("%d\n",f(n));
return 0;
}