First, Fibonacci numbers are calculated for non-negative numbers, so the parameter should be declared at least as having an unsigned int type.
The function can be written shorter. for example
#include <iostream> unsigned int fibonacci( unsigned int n ) { return n < 2 ? n : fibonacci( n - 2 ) + fibonacci( n - 1 ); } int main() { const unsigned int N = 10; for ( unsigned int i = 0; i < N; i++ ) { std::cout << i << ": " << fibonacci( i ) << std::endl; } return 0; }
The output of this program is as follows.
0: 0 1: 1 2: 1 3: 2 4: 3 5: 5 6: 8 7: 13 8: 21 9: 34
The recursive function call can be represented as follows.
fibonacci( 6 ) = fibonacci( 5 ) + fibonacci( 4 ) fibonacci( 5 ) = fibonacci( 4 ) + fibonacci( 3 ) fibonacci( 4 ) = fibonacci( 3 ) + fibonacci( 2 ) fibonacci( 3 ) = fibonacci( 2 ) + fibonacci( 1 ) fibonacci( 2 ) = fibonacci( 1 ) + fibonacci( 0 ) fibonacci( 1 ) = 1 fibonacci( 0 ) = 0
Or you can think of it as a tree, where the leaves will be calls to a function with arguments 0 or 1, since these calls no longer call the function recursively.
6 ------------------------------------------ | | 4 + 5 ------------------- ------------------- | | | | 2 + 3 3 + 4 --------- --------- --------- --------- | | | | | | | | 0 + 1 1 + 2 1 + 2 2 + 3 ----- ----- ----- ----- | | | | | | | | 0 + 1 0 + 1 0 + 1 1 + 2 ----- | | 0 + 1
If we sum up, for example, for the left branch, starting with the number 4, then we get that Fibonacci( 4 ) is equal (we will use a symmetric tree walk)
( 0 + 1 ) + ( 1 + ( 0 + 1 ) ) == 3
if (n==1::n==2)string, explicitly||instead of::. And yes, for such a code I would tear off my hands ... So you can write only in a small number of languages that are optimized. - pavel