language-agnosticcode-golffibonaccirosetta-stone

Fibonacci Code Golf


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

Solution

  • RePeNt, 9, 8 chars

    1↓[2?+1]
    

    Or 10 chars with printing:

    1↓[2?+↓£1]
    

    Run using:

    RePeNt "1↓[2?+1]"
    

    RePeNt is a stack based toy language I wrote (and am still improving) in which all operators/functions/blocks/loops use Reverse Polish Notation (RPN).

    Command      Explanation                                              Stack
    -------      -----------                                              -----
    
    1            Push a 1 onto the stack                                  1
    ↓            Push last stack value                                    1 1
    [            Start a do-while loop                                    1 1
    2?           Push a two, then pop the 2 and copy the last 2 stack     1 1 1 1
                 items onto the stack
    +            Add on the stack                                         1 1 2
    ↓£           Push last stack value then print it                      1 1 2
    1            Push a 1 onto the stack                                  1 1 2 1
    ]            Pop value (1 in this case), if it is a 0 exit the loop   1 1 2
                 otherwise go back to the loop start.
    

    The answer is on the stack which builds itself up like:

    1 1
    1 1 2
    1 1 2 3
    1 1 2 3 5
    

    It never terminates (it has the eqivilent of a C#/JAVA do { } while(true) loop) because the sequence will never terminate, but a terminating solution can be written thus:

    N_1↓nI{2?+}
    

    which is 12 chars.

    I wonder if anyone will ever read this :(