The Recursive Algorithms of the Fibonacci sequence are familiar to everyone:
// The value of item n in the Fibonacci sequence
// Recursive Algorithm
Unsigned int fib1 (unsigned int N)
{
If (n = 1 | n = 2)
Return 1;
Else
Return fib (n-1) + fib (n-2 );
}
The disadvantage of recursive algorithms is that the efficiency is too low. The following is a non-recursive algorithm:
// The value of item n in the Fibonacci sequence
// Non-recursive algorithm
Unsigned int fib2 (unsigned int N)
{
Unsigned int nret, NP, NPP; nret = NP = NPP = 1;
If (n = 1) | (n = 2 ))
Return nret;
For (unsigned int I = 3; I <= N; I ++)
{
Nret = NP + NPP;
NPP = NP;
NP = nret;
}
Return nret;
}
Fibonacci (Fibonacci) sequence:
FIB (n) = fib (n-1) + fib (n-2), n> 1, FIB (1) = fib (2) = 1
That is, the first and second items of the sequence are 1, starting from the third item, and the last one is the sum of the first two items.
The first eight items of the sequence are:
1, 1, 2, 3, 5, 8, 13, 21