# Fibonacci numbers (C)

### From LiteratePrograms

**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.

## Contents |

## Implementation

The [fibonacci] numbers in C:

<<fib.c>>=includes fib fastfib main

<<includes>>=#include<stdio.h>

## Recursive

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

<<fib>>=unsignedintfib(unsignedintn){returnn < 2 ? n : fib(n-1) + fib(n-2);}

## Iteration

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.

<<fastfib>>=unsignedintfastfib(unsignedintn){unsignedinta[3];unsignedint*p=a;unsignedinti;for(i=0; i<=n; ++i){if(i<2) *p=i;else{if(p==a) *p=*(a+1)+*(a+2);elseif(p==a+1) *p=*a+*(a+2);else*p=*a+*(a+1);}if(++p>a+2) p=a;}returnp==a?*(p+2):*(p-1);}

This iteration implementation is fast and easy to understand.

<<fastfib_v2>>=unsignedintfastfib_v2 (unsignedintn){unsignedintn0 = 0;unsignedintn1 = 1;unsignedintnaux;unsignedinti;if(n == 0)return0;for(i=0; i < n-1; i++){naux = n1; n1 = n0 + n1; n0 = naux;}returnn1;}

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 *int*s can only hold the first 92 Fibonacci numbers.

## Test driver

<<main>>=intmain(){unsignedintn;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));return0;}

Download code |