Fibonacci numbers (ALGOL 68)

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.


Contents

Implementation

The [fibonacci] numbers in ALGOL 68:

<<fib.a68>>=
fib;
fastfib;
fastfib v2;
main

Recursive

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

<<fib>>=
PROC fib = (INT n)INT:
(
  n < 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>>=
PROC fastfib = (INT n)INT:
(
  CASE n+1 IN
    0, 1
  OUT
    []INT init = (0, 1);
    [0:1]INT cache := init[@0];
    FOR i FROM UPB cache + 1 TO n DO
      cache[i MOD 2] := cache[0] + cache[1]
    OD;
    cache[n MOD 2]
  ESAC
)

This iteration implementation is fast and easy to understand.

<<fastfib v2>>=
PROC fastfibv2 = (INT n)INT:
(
  IF n = 0 THEN
    0
  ELSE
    INT n0 := 0, n1 := 1, naux;
    FOR i FROM 2 TO n DO
      naux := n1;
      n1 := n0 + n1;
      n0 := naux
    OD;
    n1
  FI
)

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 ALGOL 68 ints can only hold the first 92 Fibonacci numbers. Note: ALGOL 68G LONG LONG INT can be set to any level of precision are run time.

Test driver

<<main>>=
main:
(
  FOR n FROM 0 TO 3*4 DO printf(($"fib("g")="gl$, n, fib(n))) OD;
  FOR n FROM 0 TO 34 DO printf(($"fastfib("g")="gl$, n, fastfib(n))) OD;
  FOR n FROM 0 TO 34 DO printf(($"fastfib2("g")="gl$, n, fastfib v2(n))) OD
)
Download code
Views