Fibonacci numbers (C)

From LiteratePrograms

Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

1 \\ \end{cases} ."/>

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.



The [fibonacci] numbers in C:



This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion.

unsigned int fib(unsigned int n)
	return n < 2 ? n : fib(n-1) + fib(n-2);


This is a faster, but also much more complicated way to calculate fibonacci numbers. The result from the 2 last calculations are stored in an array, to avoid all the recalculations in the recursive implementation.

unsigned int fastfib(unsigned int n)
	unsigned int a[3];
	unsigned int *p=a;
	unsigned int i;
	for(i=0; i<=n; ++i) {
		if(i<2) *p=i;
		else {
			if(p==a) *p=*(a+1)+*(a+2);
			else if(p==a+1) *p=*a+*(a+2);
			else *p=*a+*(a+1);
		if(++p>a+2) p=a;
	return p==a?*(p+2):*(p-1);

This iteration implementation is fast and easy to understand.

unsigned int fastfib_v2 (unsigned int n)
  unsigned int n0 = 0;
  unsigned int n1 = 1;
  unsigned int naux;
  unsigned int i;
  if (n == 0)
    return 0;
  for (i=0; i < n-1; i++) {
    naux = n1;
    n1 = n0 + n1;
    n0 = naux;
  return n1;

Note that even this implementation is only suitable for small values of n, since the Fibonacci function grows exponentially and even on a 64-bit machine signed C ints can only hold the first 92 Fibonacci numbers.

Test driver

int main()
	unsigned int n;
	for(n=0; n<35; ++n) printf("fib(%u)=%u\n", n, fib(n));
	for(n=0; n<35; ++n) printf("fastfib(%u)=%u\n", n, fastfib(n));
        for(n=0; n<35; ++n) printf("fastfib_v2(%u)=%u\n", n, fastfib(n));
	return 0;
Download code