Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, f
, which prints the Fibonacci numbers.
Starting point: 25 14 characters in Haskell:
f=0:1:zipWith(+)f(tail f)
f=0:scanl(+)1f
Language: dc, Char count: 20
Shorter dc solution.
18 characters of English..
"Fibonacci Sequence"
ok, I fail. :)
13 chars of Golfscript:
Update to explain the operation of the script:
2,
makes an array of[0 1]
~
puts that array on the stackdo
, we start the stack off with0 1
(1 at top of stack)The
do
loop:.
duplicates the top item of the stack; here, we do this twice (leaving us with0 1 1 1
on initial run)p
prints the topmost value (leaving us with0 1 1
)@
rotates the top 3 items in the stack, so that the third-topmost is at the top (1 1 0
)+
adds the top 2 items in the stack (leaving1 1
).
duplicates the top value, so that thedo
loop can check its truthiness (to determine whether to continue)Tracing this mentally a couple of loops will be enough to tell you that this does the required addition to generate the Fibonacci sequence values.
Since GolfScript has bignums, there will never be an integer overflow, and so the top-of-stack value at the end of the
do
loop will never be 0. Thus, the script will run forever.@Andrea Ambu
An iterative pythonic
fibonacci()
's version should look something like that:The previous Ruby example won't work w/o either semicolons or newlines, so it's actually 32 chars. Here's the first example to actually output the sequence, not just return the value of a specified index.
Ruby:
53 chars, including newlines:
or if you want function that outputs a usable data structure, 71 chars:
or accepting command-line args, 70 chars:
80 characters, but truly generates the sequence, in linear time.