Fibonacci numbers (dc)

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 dc:
This program will calculate all Fibonacci numbers up to a given max value, and the number following that.

Contents

Setup

We store the 2 first Fibonacci numbers on the primary stack.

<<fib.dc>>=
0p 1p

The max value is stored in register S.

<<fib.dc>>=
10000000000000000000sS

Macro definition

A macro for calculating the next Fibonacci number is stored in register m.
The macro ends in a command to execute itself, if register S is greater than the number on top of the stack. This is how we implement loops in dc.

<<fib.dc>>=
[sa d la + sr la lr p  d lS >m]sm

Running the macro

This command will execute the macro stored in register m.

<<fib.dc>>=
lmx

Running the script

This is how to execute this script:

dc <fib.dc

Note: dc does not like extra carriage-return characters at end of line, so downloading it with Windows file encoding will give you some error messages.

Download code
Views