views:

3011

answers:

32
+12  Q: 

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 characters in Haskell:

f=0:1:zipWith(+)f(tail f)
+8  A: 

22 characters with dc:

1[pdd5**v1++2/lxx]dsxx

Invoke with either:

dc -e'1[pdd5**v1++2/lxx]dsxx'

Or:

echo '1[pdd5**v1++2/lxx]dsxx' | dc

Note: not my work, poached from perlmonks.

Chris Young
does not work here :( the code on perlmonks does though
knittl
+19  A: 

13 chars of Golfscript:

2,~{..p@+.}do

Update to explain the operation of the script:

  1. 2, makes an array of [0 1]
  2. ~ puts that array on the stack
  3. So, at the time we run the do, we start the stack off with 0 1 (1 at top of stack)

The do loop:

  1. Each . duplicates the top item of the stack; here, we do this twice (leaving us with 0 1 1 1 on initial run)
  2. p prints the topmost value (leaving us with 0 1 1)
  3. @ rotates the top 3 items in the stack, so that the third-topmost is at the top (1 1 0)
  4. + adds the top 2 items in the stack (leaving 1 1)
  5. . duplicates the top value, so that the do 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.

Chris Jester-Young
That's the value of using the right tool for the right problem. Abd then... is the problem really relevant?
rshimoda
You wanna talk about "right tool"? See the winning entry for http://stackoverflow.com/questions/62188 :-)
Chris Jester-Young
What does it even do? I bet no one looks at my answer.
Callum Rogers
@Callum: Unlike your answer (which I now did look at), mine actually prints the numbers (even if the program runs endlessly). :-P I'll update the post to say what the script does.
Chris Jester-Young
Thanks for explaining what it does - it seems our solutions are very similar. I added printing, but I still consider that you won (I am a year late :)
Callum Rogers
+30  A: 

18 characters of English..

"Fibonacci Sequence"

ok, I fail. :)

Krakkos
You could easily remove 5 characters - "fibonacci seq"..
dbr
@dbr: or remove 11 characters - "fib seq"
Lucas Jones
wow, 190 rep, out of 201.
Malfist
+6  A: 

For the record:

  • Lua (66 chars): function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end
  • JavaScript (41 chars): function f(n){return n<2?n:f(n-1)+f(n-2)}
  • Java (41 chars): int f(int n){return n<2?n:f(n-1)+f(n-2);}

I am not much adept of super concise languages... :-P

Chris is right, I just took the simple, recursive algorithm. Actually, the linear one is even shorter in Lua (thanks to multiple assignment)! JavaScript isn't so lucky and Java is worse, having to declare vars...

  • Lua (60 chars): function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end
  • JavaScript (60 chars): function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b}
  • Java (71 chars): int f(int n){int a=1,b=0,i=0;for(;i++<n;){int x=a+b;a=b;b=x;}return b;}

I would write Lua's code with local a,b=1,0 but it is longer, so let's pollute _G! ;-) Idem for JS.

For completeness, here are the terminal recursive versions. Lua's one, using tail call, is as fast as the linear one (but 69 chars, it is the longest!) - need to call them with three params, n,1,0.

  • Lua (69 char, longer!): function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end
  • JavaScript (44 chars): function f(n,a,b){return n<1?b:f(n-1,b,a+b)}
  • Java (52 chars): int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}
PhiLho
I bet you my Golfscript implementation is faster than any of yours, for large N. Not because Golfscript is fast (it's quite slow, in fact), but because my solution doesn't do recursion. :-P
Chris Jester-Young
You are right, and it is even shorter for Lua! Java[Script]'s recursive versions are "better" for the challenge of conciseness...
PhiLho
+7  A: 

Python, 38 chars.

f=lambda n:n if n<2 else f(n-1)+f(n-2)

Not so short but the most readable in my opinion :P

EDIT: Here is the iterative way (if someone needs to see it in python :-)

f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
Andrea Ambu
Your iterative way is not very suitable for generating the Fibonacci's *sequence*. See http://stackoverflow.com/questions/232861/fibonacci-code-golf#250041
J.F. Sebastian
It's not iterative but analytic
Dario
+13  A: 

Perl 6 - 22 characters

sub f{1,1...{$^a+$^b}}

mpeters
A: 

Not the shortest, but the fastest at the time of posting. :-)

float f(float n) {
    return (pow(1+sqrt(5.0))/2.0),n) - pow(1+sqrt(5.0))/2.0),n)/sqrt(n));
}
mstrobl
It does not work.
Andrea Ambu
I think he means to fix the parentheses and have the second be 1 - sqrt(5.0). This is the fastest for a given n, but it is slower for generating a sequence, and also it won't work for numbers with more than a pretty small amount of digits.
Claudiu
Two typos. Sorry, this should work:(pow((1+sqrt(5.0)))/2.0),n) - pow((1-sqrt(5.0)))/2.0),n)/sqrt(n));
mstrobl
Ack, sorry Claudiu. Did not read your answer before posting. Claudiu is right, although it's wrong that it is slower for generating a sequence. For a sequence of n it's O(n). Fibonacci's recursion is much higher than that, unless you do not recalculate the results previously calculated.
mstrobl
If your intent is to generate a sequence, you would not need to recalculate any results -- you'd be saving them, in the sequence.
ephemient
@mstrobl: the haskell in the question, for example, doesn't recalculate previous results, so I think it would indeed be faster since it only performs additions.
Claudiu
+8  A: 

J, 27 characters for a non-recursive function:

f=:3 :'{:}.@(,+/)^:y(0 1x)'

+/ sums over a list.
(,+/) appends the sum of a list to its tail.
}.@(,+/) sums a list, appends an element to its tail, and drops the first element.
}.@(,+/)^:y iterates the above function y times.
}.@(,+/)^:y(0 1x) applies the above function to the list (0,1) (the x makes it an integer).
{:}.@(,+/)^:y(0 1x) takes the last element of the output list of the above.
f=:3 :'{:}.@(,+/)^:y(0 1x)' defines f to be a function on one variable y.

ephemient
how does "f=:3 :'______'" define a function to be of one variable y? Where does the :3 come from? ahh! (head exploding).
Claudiu
Heh, J is quite interesting, isn't it? All functions are unary (taking implicit 'y' argument) or binary (taking implicit 'x' an 'y') or both (well, in J terms, all verbs can be used as monads or dyads). "3 :" introduces the definition of a monadic verb.
ephemient
+1  A: 

33 characters in C:

F(n){return n<2?n:F(n-1)+F(n-2);}
Adam Rosenfield
+3  A: 

Generate the Fibonacci sequence. sequence SEQUENCE!

That's not an answer... But the remark is valid.
PhiLho
+3  A: 

Ruby (30 characters):

def f(n)n<2?n:f(n-1)+f(n-2)end
Firas Assaad
+3  A: 

@Andrea Ambu

An iterative pythonic fibonacci()'s version should look something like that:

def fibonacci(a=0, b=1):
    while True:
        yield b
        a, b = b, a+b
J.F. Sebastian
+5  A: 

Windows XP (and later versions) batch script. This batch function when given a single argument - amount, generates amount+1 Fibonacci numbers and returns them as a string (BATCH doesn't really have sets) in variable %r% (369 characters, or 347 characters - if we remove indentation):

:f
    set i=0
    set r=1
    set n=1
    set f=0
    :l
     if %n% GTR %~1 goto e
     set f=%f% %r%
     set /A s=%i%+%r%
     set i=%r%
     set r=%s%
     set /A n+=1
     goto l
    :e
    set r=%f%
    exit /B 0

And here's the complete script, to see it in action (just copy-past it into a CMD or BAT file and run it):

@echo off
call :ff 0
call :ff 1
call :ff 2
call :ff 3
call :ff 5
call :ff 10
call :ff 15
call :ff 20
exit /B 0

:ff
    call :f "%~1"
    echo %~1: %r%
    exit /B 0

:f
    set i=0
    set r=1
    set n=1
    set f=0
    :l
     if %n% GTR %~1 goto e
     set f=%f% %r%
     set /A s=%i%+%r%
     set i=%r%
     set r=%s%
     set /A n+=1
     goto l
    :e
    set r=%f%
    exit /B 0
Paulius Maruška
+1  A: 

Delphi Prism (Delphi for .net)

f:func<int32,int32>:=n->iif(n>1,f(n-1)+f(n-2),n)

49 chars

Steve
+1  A: 

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:

def f(n);n<2?1:f(n-1)+f(n-2);end
0.upto 20 {|n|p f n}

or if you want function that outputs a usable data structure, 71 chars:

def f(n);n<2?1:f(n-1)+f(n-2);end
def s(n);(0..n).to_a.map {|n| f(n)};end

or accepting command-line args, 70 chars:

def f(n);n<2?1:f(n-1)+f(n-2);end
p (0..$*[0].to_i).to_a.map {|n| f(n)}
Lex
+3  A: 

Language: dc, Char count: 20

Shorter dc solution.

dc -e'1df[dsa+plarlbx]dsbx'
Hynek -Pichi- Vychodil
What kind of language is this :rolleyes:
Ikke
+3  A: 

C#

I'm seeing a lot of answers that don't actually generate the sequence, but instead give you only the fibonacci number at position *n using recursion, which when looped to generate the sequence gets increasingly slower at higher values of n.

using System;
static void Main()
{
  var x = Math.Sqrt(5);
  for (int n = 0; n < 10; n++)
    Console.WriteLine((Math.Pow((1 + x) / 2, n) - Math.Pow((1 - x) / 2, n)) / p) ;
}
BenAlabaster
+5  A: 

Here's my best using scheme, in 45 characters:

(let f((a 0)(b 1))(printf"~a,"b)(f b(+ a b)))
Henk
+6  A: 

Language: C++ Compiler Errors
Characters: 205

#define t template <int n> struct 
#define u template <> struct f
t g { int v[0]; };
t f { enum { v = f<n-1>::v + f<n-2>::v }; g<v> x;};
u<1> { enum { v = 1 }; };
u<0> { enum { v = 0 }; };
int main() { f<10> x; }
Eclipse
+5  A: 

F#:

(0,1)|>Seq.unfold(fun(a,b)->Some(a,(b,a+b)))

44 Chars

David Klein
+3  A: 
let rec f l a b =function 0->a::l|1->b::l|n->f (a::l) b (a+b) (n-1) in f [] 1 1;;

80 characters, but truly generates the sequence, in linear time.

huitseeker
bizarre ...
Claudiu
A: 

Euphoria: 44 characters

object f=1&1 loop do f&=f[$]+f[$-1]until 0

Keeps on generating until RAM or doubles run out.

Matt Lewis
+2  A: 

Lua - 49 chars

function f(n)return n<2 and n or f(n-1)+f(n-2)end
Nican
+6  A: 

x86 (C-callable) realmode, 14 bytes.
Input is  n  on stack, returns  Fn  in AX.

59 31 C0 E3 08 89 C3 40 93 01 D8 E2 FB C3
I. J. Kennedy
A: 

Lucid

f = 1 fby 1 fby f + prev f;

27 characters, including the spaces.

Chris Dodd
A: 

Rexx:

arg n;a=1;b=1;do i=1 to n;say a b;a=a+b;b=a+b;end

Hellion
+2  A: 

Befunge-93

31 chars

Will output an infinite list of the Fibonacci numbers, from 0 upwards, separated by tabs (could be reduced to 29 chars by deleting 9, in the first row, at the expense of no whitespace between numbers).

Unfortunately, all the Befunge-93 interpreters I've tried seem to overflow after 65k, so the output is only correct until and including 46368 (which is F24).

#v::1p1>01g:.\:01p+9,#
 >     ^

Confirmed to work (with caveat above) with the Befunge-93 interpreter in Javascript and the Visual Befunge Applet Full.

I'm proud to say this is a completely original work (i.e. I did not copy this code from anyone), and it's much shorter than the Befunge solution currently on Rosetta Code.

Mark Rushakoff
+5  A: 

Brainfuck, 33 characters:

+.>+.[<[>+>+<<-]>.[<+>-]>[<+>-]<]
Eric Mickelsen
+8  A: 

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 :(

Callum Rogers
A: 

PDP-11 Assembler (source)

    .globl  start
    .text
start:
    mov $0,(sp)
    mov $27,-(sp)
    jsr pc, lambda
print_r1:
    mov $outbyte,r3
div_loop:
    sxt r0
    div $12,r0
    add $60,r1
    movb    r1,-(r3)
    mov r0,r1
    tst r1
    jne div_loop
    mov $1,r0
    sys 4; outtext; 37
    mov $1,r0
    sys 1
lambda:
    mov 2(sp),r1
    cmp $2,r1
    beq gottwo
    bgt gotone
    sxt r0
    div $2,r0
    tst r1
    beq even
odd:
    mov 2(sp),r1
    dec r1
    sxt r0
    div $2,r0
    mov r0,-(sp)
    jsr pc,lambda
    add $2,sp
    mov r0,r3
    mov r1,r2
    mov r3,r4
    mul r2,r4
    mov r5,r1
    mov r3,r4
    add r2,r4
    mul r2,r4
    add r5,r1
    mul r3,r3
    mov r3,r0
    mul r2,r2
    add r3,r0
    rts pc
even:
    mov 2(sp),r1
    sxt r0
    div $2,r0
    dec r0
    mov r0,-(sp)
    jsr pc,lambda
    add $2,sp
    mov r0,r3
    mov r1,r2
    mov r2,r4
    mul r2,r4
    mov r5,r1
    mov r2,r4
    add r3,r4
    mul r4,r4
    add r5,r1
    mov r2,r4
    add r3,r4
    mul r2,r4
    mov r5,r0
    mul r2,r3
    add r3,r0
    rts pc
gotone:
    mov $1,r0
    mov $1,r1
    rts pc
gottwo:
    mov $1,r0
    mov $2,r1
    rts pc

    .data
outtext:
    .byte 62,63,162,144,40,106,151,142,157,156
    .byte 141,143,143,151,40,156,165,155
    .byte 142,145,162,40,151,163,40
    .byte 60,60,60,60,60
outbyte:
    .byte 12
JUST MY correct OPINION
A: 

BrainF**k:

>+++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]

That'll generate the first 5. To generate more, replace the 5 + at the beginning with more: eg:

>++++++++++++++++++++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]
Tom H
Use that http://www.iwriteiam.nl/Ha_bf_online.html there with the CN-execute button.
Tom H
A: 

Java Iterative (73)

void f(int n){for(int a=1,b=1;n-->0;b=a+(a=b)){System.out.print(a+",");}}

Ruby (46)

def f(n);a,b=1,1;1.upto(n){p a;b=a+(a=b);};end

Update: Ruby(42)

def f(n);a=b=1;n.times{p a;b=a+(a=b);};end
st0le