Fibonacci sequence: Difference between revisions
Content added Content deleted
m (→{{header|Commodore BASIC}}: Formatting) |
(→{{header|Forth}}: Add version with support for negative indexes) |
||
Line 4,625:
<lang forth>: fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ;</lang>
Or, for negative-index support:
<lang forth>: fib ( n -- Fn ) 0 1 begin
rot dup 0 = if drop drop exit then
dup 0 > if 1 - rot rot dup rot +
else 1 + rot rot over - swap then
again ;</lang>
Since there are only a fixed and small amount of Fibonacci numbers that fit in a machine word, this FORTH version creates a table of Fibonacci numbers at compile time. It stops compiling numbers when there is arithmetic overflow (the number turns negative, indicating overflow.)
|