How to Implement Fibonacci Number Algorithm using C++ Example

by Koscica Dusko on March 6, 2014

Fibonacci was an Italian mathematician who introduced this subject to European mathematics, but the similar array was mentioned even before his time.

There are two definitions of Fibonacci numbers with slight variation. Both are pretty similar but little different at the same time.

First:
0, 1, 1, 2, 3, 5, 8, …

Second:
1, 1, 2, 3, 5, 8, …

If you look closer at the above sequence, each number is constructed as the sum of previous two numbers. The first two numbers are: zero and one (or one and one).

For this article, we’ll use the first definition.

Fibonacci(0) = 0,
Fibonacci(1) = 1,
Fibonacci(2) = Fibonacci(0) + Fibonacci(1) = 0 + 1 = 1
Fibonacci(3) = Fibonacci(1) + Fibonacci(2) = 1 + 1 = 2
Fibonacci(4) = Fibonacci(2) + Fibonacci(3) = 1 + 2 = 3

Fibonacci(n) = Fibonacci(n-2) + Fibonacci(n-1).

Implementation of Fibonacci Number

There are many ways you could create the array of Fibonacci, but I will show two most common methods.

The first approach is to use the recursive implementation. For this, you should spot the pattern and apply it to the function as shown below.

long long 
FibonacciElement( long long n)
{
  if (n==0) return 0;
  if (n==1) return 1;
  return FibonacciElement(n-2) + FibonacciElement(n-1);  
}

Now, I strongly recommend you to take 8-th element of the Fibonacci sequence and calculate it with binary tree structure in the textbook or in some program that will be suitable for that task.

As you analyze it you should notice that there are elements that are calculated few times, this is one of the reasons why this approach will be slower, that problem could be solved if you use compiler that has memorization built in, sometimes you need to use few adjustments.

The second approach will not use the self calling of the function as shown below:

long long
FibonacciElement2( long long n)
{
   long long Previous   = 0,
             PPrevious  = 1;

long long i=2, Curent;
while( i <= n)
{
	Curent      = PPrevious + Previous;
	PPrevious = Previous;
	Previous   = Curent;
	++i;
}

	return Curent;
}

Recursive implementation is usually slower than those which don’t have self called functions. And that is another discussion, we will not enter into that matter, but I think that it would be good time for the short story.

#include <iostream>

using namespace std;

long long FibonacciElement1(long long);
long long FibonacciElement2(long long);

int
main(void)
{
	cout<<"Calculate Fibonacci element"<<endl
		<<"enter the n -";
        long long int lliN; cin>>lliN;

	cout<<"With recursion F(n)    ="<<FibonacciElement1(lliN)<<endl
	    <<"Iterative solution F(n)="<<FibonacciElement2(lliN)<<endl;

	int iRespond; cin>>iRespond;

	return EXIT_SUCCESS;
}

long long 
FibonacciElement1( long long n)
{
  if (n==0) return 0;
  if (n==1) return 1;
  return FibonacciElement1(n-2) + FibonacciElement1(n-1);  
}

long long
FibonacciElement2( long long n)
{
   long long Previous   = 0,
             PPrevious  = 1;

if( n==0) return 0;
if( n==1) return 1;

long long i=1, Curent;
while( i <= n)
{
	Curent      = PPrevious + Previous;
	PPrevious   = Previous;
	Previous    = Curent;
++i;
}
return Curent;
}

We have discussed what Fibonacci numbers are, and we have seen two ways to calculate them.

I recommend that you do further research on this subject by digging little deeper. This algorithm has some practical application as well.

Additional Exercises:

  1. Create and display first n Fibonacci numbers, use first and second definition.
  2. Display n-th Fibonacci number: in binary form, in hexadecimal form and in octal form.
  3. Create the vector with n Fibonacci numbers.
  4. Construct similar array like Fibonacci array but use: a and b, as first two numbers.
  5. Form the sequence that is like the Fibonacci array, with tree first elements equal to: 1, 1 and 1.
  6. Approximate n-th Fibonacci number with some approximation formula, and if you could create one on your own it would be even better.
  7. Find the sum of first n Fibonacci numbers.

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 22 comments… read them below or add one }

1 Kiffin March 7, 2014 at 4:48 am

Wow that sure is alot of code for such a simple algorithm. In Ruby for example, the same code above can be replaced by the following one-liner:

f = ->(x){ x 8

So I’d say that while C/C++ is good for many things, this is definitely not one of them.

2 cybernard March 7, 2014 at 7:25 am

The question is not how to implement it, but what practical and/or useful real life benefit does it provide? Seems like a waste of time.

3 gigglingsomnambulist March 7, 2014 at 10:24 am
4 deniz gezmis March 7, 2014 at 10:44 am

cybernard you are so wrong about topic. Just google “fibonacci numbers in nature” and see how it is beneficial, next to you, and how wrong you are.

5 SeattleC++ March 7, 2014 at 11:43 am

The fibonacci sequence grows about as fast as n squared, but it doesn’t require any multiplications to compute. It’s thus useful on small or low-power processors where addition is fas and multiplication is slow. One of many things it’s useful for is implementing exponential backoff and retry in communication. In normal use, you compute fibonacci(n), already knowing fibonacci(n-1) and fibonacci(n-2). This computation requires only a single addition.

The fibonacci sequence is one of those obscure corners of math that you can live your whole life without knowing, but once you know it, you use it over and over again.

C++ Style Notes

The Fibonacci sequence is only defined over positive integers. The argument to FibonacciElement1() should be unsigned. As coded, FobonacciElement1() will run away dangerously for any negative value of n.

Your computer is not big enough to compute the fibonacci sequence recursively for large values of n, because the stack will have n stack frames on it. Even the iterative computation would take too long for large values of n. I recommend coding FibonacciElement1() with an argument of type “unsigned”, which is “unsigned int”. Since fibonacci(n) is approximately equal to n squared, you have to decide whether you want to attempt to run this code for large n. If you do, your result type has to have about twice as many bits as your argument type. Since this is infeasible as noted above, it’s reasonable for it to return “unsigned” as well.

Here’s a revised version that is safer. Note the recursive version is still wastefully inefficient. You may recode FibonacciElement2() as an exercise :-) .

unsigned
FibonacciElement1a(unsigned n)
{
if (n==0) return 0;
if (n==1) return 1;
return FibonacciElement1(n-2) + FibonacciElement1(n-1);
}

6 duskoKoscica March 7, 2014 at 1:29 pm

@cybernard, Well, your statement is very vague and I just don’t have enough information to have any conclusion what so ever. When you say “waist of time” this is like something that make me wonder!

@Deniz Gezmis, You really understand the thing, just read the article, do the exercises and if you come up with something interesting sare with others.

@Seattle C++, You have a lot of knowledge and wery sharp eye for detailes to. Good work. One more thing, there is a approximation for n-th element of the Fibbonachi array, if you need that to I could post it, but with more carefull search that thing should be found on Internet. Happy Hacking People!!!

7 duskoKoscica March 7, 2014 at 2:32 pm

Does anybody know the formula for estimation of ciphers of n-th Fibbonachi! Tried google and some others but just would not show it.

8 duskoKoscica March 7, 2014 at 11:14 pm

@Kiffin Well if you say something like f=->{x8 is it olready bilt in so that you just call the some thing, or did you add some library long before and now you have forgoten about it or somethin like that. Well then you could say that if somebody is developing the numericall algorithms in C++ that is vaist of time just because ther are the progams like Matlab and some other ones. Be more specific!

9 duskoKoscica March 7, 2014 at 11:27 pm

@Kiffin well I habe never meet any Kiffins eather but I have noticed that you have mention copy destructor on your site. Please could you be more elaborat on this one because I have never seen that thing eather, there are copy constructors but I have never heard of copy destructor, have heard of virtual ones. Interesting subject indead!

10 Kiffin March 8, 2014 at 8:42 am

Sorry, but the code I added in my comment got botched because of the special characters. Does code work?

11 Kiffin March 8, 2014 at 8:44 am

f = ->(x){ x < 2 ? x : f[x-1] + f[x-2] }
puts f[5]

12 duskoKoscica March 8, 2014 at 9:46 am

From point of wiev that you cold create faster code, I would disagree! The aproximation algorithm is way easier to implement and faster, saves memory and so on. This is more exercize thing, as you might notice.

This is one array of cyphers it has something to do with Fibonachi array to, it is for execize>0112358314593471897639213… one more thing to do with it is to check is it periodicall or not. Have funn!

Well aproximation would bit that line any time, speed or what so ever!

13 Anonymous March 9, 2014 at 10:16 pm

template struct Fibonacci
{
enum { value = (Fibonacci::value + Fibonacci::value) };
};

template struct Fibonacci
{
enum { value = 1 };
};

template struct Fibonacci
{
enum { value = 1 };
};

template struct Fibonacci
{
enum { value = 1 };
};

int main()
{
int x = Fibonacci::value;
cout << x << endl;
int x
}

14 duskoKoscica March 11, 2014 at 6:54 am

Ok, so>

15 FOK March 11, 2014 at 9:58 am

For task like computing fibnacci numbers you can still use recursive algorithm without coputational explosion. What you need is to be able to return more than one value. In C++ you can use structures like vectors.

See following rework of the code that can compute fibonacci numbers recursively withhout problems described in article. This version is as fast as iterative version.

#include <iostream>
#include <vector>

using namespace std;

vector<long long> FibonacciElement(long long);

int
main(void)
{
    cout<<"Calculate Fibonacci element"<<endl
        <<"enter the n - ";
        long long int lliN; cin>>lliN;

    cout<<"With recursion F(n)    ="<<FibonacciElement(lliN)[1]<<endl;

    int iRespond; cin>>iRespond;

    return 0;
}

vector<long long>
FibonacciElement( long long n)
{

  if (n==0) return vector<long long> { 0, 0 };
  if (n==1) return vector<long long> { 0, 1 };
  vector<long long> fib = FibonacciElement(n-1);
  long long tmp = fib[0];
  fib[0] = fib[1];
  fib[1] = fib[0] + tmp;
  return fib;
}
16 duskoKoscica March 11, 2014 at 11:40 am

Nice stuff!

THX a lot FOK!

Even do it is done before it will improve the article!

17 duskoKoscica March 12, 2014 at 12:49 am

One more clarification, when I think about the recurzion I like to think about tree different points of view, yes there are some other points of view but somehow they are not so important> what is mathematical definition of recursion, you will see the difference if you anayze the n! definition, the secont is how programmer code it, you have nicely presnted one more way that will produce the code that has less calculations, the third and it might be the most importent is how it is translated into executable bfile withsome optimizations it could be very fast but it coud be done more on that fild if that thiong is not done a. The next big thing is mutithreading, but that is another big topicc.

18 duskoKoscica March 12, 2014 at 1:34 am

And if did not say that, when you apply the selfcaled function there are a lot of copies of that function, the stack gets overused, this is traditional view of point, if this could be avoided to then you could really writte nice code and get the very fast results… endles story indead. expanation of the recursion in two steps> 1. look at the second step for information what is the recursion. 2. if you have not get it yet return back to the first step. This is bit funny. Fore real thing there is formal matematical definition to!

19 duskoKoscica March 13, 2014 at 12:05 pm

One more coment on this subject, it has a lot of applications in real life, but there is one more thing to go with this article, and this way it would not be said. Well, you could array-s for big numbers, then you could calculate the Fibonacci elemente even beyond the limits of the long long int, the unsigned one, or any data type that would be provided to you by defaults…

20 FOK March 14, 2014 at 3:21 pm

@duskoKoscica yes, you are right, for such calculations might be recurisve algorithm bit of problem. Too deep recursion is always problem and can cause troubles. I would prefer your iterative version over my recursive.
What I wanted to show with my code was that some tasks require returning more than one value. And for such case it is useful to use complex data types.
In some languages, like perl, it is possible to return just arrays of data.
I have read that some functional programming languages do function call results caching. So if you e.g. call fib(5), then on call fib(6) it will just calculate sum of two cached values for fib(5) and fib(4). I think that this problem is perfect fit for such feature.

21 duskoKoscica March 15, 2014 at 1:13 am

@Fok I am very thankfull for your information, the way to calculate the Fib in the way you have shown is great thing. Recursion is great to. But there are some solutions that are good from point of speed, and some are just intelectual teazers, you should learn feaw of them to. In my next article about prime numbers it is just the path for the people to look for other ways. In the way this was just the small push toward the goal each of readers shoule achieve. Because we are not the same and we have some preferences, the result should be different but it is the way thing work!

22 duskoKoscica April 5, 2014 at 12:04 am

And one more thing about Fib nums. There is very easy way to check if the given number is Fib num. Try to google it.

Leave a Comment

Previous post:

Next post: