Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write the shortest code that either:

  • Generates a Fibonacci sequence (either in standard output, or as a stream)
  • Calculates, given n, the nth Fibonacci number

(I gave both options in case one is easier to do in your chosen language than the other.)


Edit: for the avoidance of doubt, a stream or sequence is infinite in length (I'm sorry that there are a couple of non-functional programmers who answered this question in a cheeky way). For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minumum) has to be supported.

share|improve this question
Maybe no need of cloning SO questions? stackoverflow.com/questions/232861/fibonacci-code-golf – Nakilon Jan 28 '11 at 2:41
1  
@Nakilon: Well, that question is dead already (I know this, because my answer was the accepted one :-P). I wanted to see if anyone could improve upon the 13-character GolfScript solution. – Chris Jester-Young Jan 28 '11 at 2:45
To make answers comparable, there schould be just one form of the question, IMHO. – user unknown Apr 12 '11 at 1:29

53 Answers

1 2
up vote 19 down vote accepted

GolfScript, 12

Now, just 12 characters!

1.{[email protected]+.}do
share|improve this answer
+1 nice work. If you make it shorter than 13 chars, I'll instantly accept your answer (unless someone makes an even shorter answer, of course). :-P – Chris Jester-Young Jan 29 '11 at 23:54
1  
I love a challenge. Done! ;-) – jtjacques Jan 30 '11 at 0:10
Nice, you win. At least, until someone makes something even shorter (if that's even possible). :-P – Chris Jester-Young Jan 30 '11 at 0:33
1  
that definition is almost as short as the name 'Fibonacci' itself! +1 – agent-j Jun 18 '12 at 18:21

C#: 38 (40 to ensure non-negative numbers)

Inspired by the beauty of Jon Skeet's C# answer and St0le's answer, another C# solution in only 38 characters:

Func<int,int>f=n=>n>2?f(n-1)+f(n-2):1;

Tested with:

for(int i = 1; i <= 15; i++)
    Console.WriteLine(f(i));

Yay for recursive Func<>! Incorrect when you pass in negative numbers, however - corrected by the 40 character version, which doesn't accept them:

Func<uint,uint>f=n=>n>2?f(n-1)+f(n-2):1;

Note: as pointed out by @Andrew Gray, this solution doesn't work in Visual Studio, as the compiler rejects the in-line function definition referring to itself. The Mono compiler at http://www.compileonline.com/compile_csharp_online.php, however, runs it just fine. :)

Mono Compilation

Visual Studio: 45

Func<int,int>f=null;f=n=>n>2?f(n-1)+f(n-2):1;
share|improve this answer
looks rather familiar...dunno where I've seen that before... ;) As far as I can tell, though, in C# this is the best way of doing it. However, your way won't work - you have to assign null to your function to use a recursive lambda. As that code stands, it won't compile, with a syntax error 'use of unassigned function f' at the line that your lambda is being defined at. – Andrew Gray Apr 17 at 18:14
1  
Depends on your compiler. :) It does exactly as you say in Visual Studio - but the Mono compiler at compileonline.com/compile_csharp_online.php runs it perfectly as-is. – Troy Alford Apr 17 at 18:45
1  
Didn't know that. I wonder why VS and Mono went two different directions on this one...or, maybe the Mono guys are just smarter. The answer is beyond me. D: – Andrew Gray Apr 17 at 18:49
Updated to clearly point out our findings. ;) – Troy Alford Apr 17 at 18:53

<>< - 15 characters

0:nao1v LF a+@:n:<o
share|improve this answer
Yay for ><>! I always give ><> answers +1, so no exception :) – tomsmeding Mar 18 at 6:42
Though you can shorten it to 0:nao1v LF a+@:n:<o if you want to. Gives 15 :) In fact, this also makes the output slightly more readable... – tomsmeding Mar 18 at 7:28

C#: 83 69 68 66 58 53

I used a nasty trinary and recursive lambda expression to achieve this one.

Source: StackOverflow

Func<ulong,ulong> f=null;f=x=>(x<2)?x:f(x-2)+f(x-1);

Usage:

    public static void Main()
    {
        // Recursive lambda expression...
        Func<ulong, ulong> f = null;
        f = x => (x < 2) ? x : f(x - 2) + f(x - 1);

        Console.WriteLine("Please enter a whole number to obtain the Fibonacci sequence number for:");
        string value = Console.ReadLine();

        long numValue;
        if(UInt64.TryParse(value, out numValue))
            Console.WriteLine(f(numValue));

        Console.WriteLine("Press any key to end the program.");
        Console.ReadKey();
    }
share|improve this answer
2  
You don't have no support negative indices. Also, the "ternary" conditional operator isn't nasty if you use it right. :-) – Chris Jester-Young Apr 8 at 15:21
That helps, thanks! I don't consider ternaries nasty usually, but in a case like the one I've posted, I would do everything in my power to avoid that getting into a codebase. It gets points for clever/short, but not readable. – Andrew Gray Apr 8 at 15:28
1  
lol - I posted mine without ever seeing yours. Funny to see that they're almost identical. :) – Troy Alford Apr 17 at 17:54
1  
Yeah, but trying to calculate anything above f(45) will cause either a StackOverflow, or just take forever and some time to calculate. – Andrew Gray Apr 17 at 18:09

Python

def fibo(n):
    a, b = 0, 1
    for i in range(1, n+1):
        a, b = b, a+b
        print str(i) + ': ' + str(a)
share|improve this answer
2  
Welcome to Programming Puzzles & Code Golf, @user7725. Please note that code golf is a challenge of writing the shortest code possible. That means, here we write unindented and almost unreadable code and force the limits of the language syntax to shorten our codes as possible. – manatwork Apr 9 at 6:43

Mathematica,26 chars

If[#>1,#0[#-1]+#0[#-2],#]&
share|improve this answer

APL: 26 characters

This is a function which will print out the n and n-1 Fibonacci numbers:

{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}

For example,

{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}13

yields the vector:

233 144
share|improve this answer
Surely, with APL's prodigious operator vocabulary, it should be able to compete in size with the GolfScript one? ;-) – Chris Jester-Young Apr 8 at 11:32
@ChrisJester-Young Oh probably, but I only started learning APL today... – SL2 Apr 8 at 23:41

C: 48 47 characters

A really really truly ugly thing. It recursively calls main, and spits out warnings in any sane compiler. But since it compiles under both Clang and GCC, without any odd arguments, I call it a success.

b;main(a){printf("%u ",b+=a);if(b>0)main(b-a);}

It prints numbers from the Fibonacci sequence until the integers overflow, and then it continues spitting out ugly negative and positve numbers until it segfaults. Everything happens in well under a second.

Now it actually behaves quite well. It prints numbers from the Fibonacci sequence and stops when the integers overflow, but since it prints them as unsigned you never see the overflow:

VIC-20:~ Fors$ ./fib
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352
24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170
1836311903 2971215073 VIC-20:~ Fors$
share|improve this answer
Printing out overflowed numbers and/or segfaulting is probably not part of the spec, but nice try. :-) – Chris Jester-Young Apr 4 at 11:53
Certainly, but it's not the only solution here that segfaults. :) I will edit it so that it behaves more properly, since I got the character count down anyway. – Fors Apr 4 at 13:09
Yay! Have an upvote. :-) – Chris Jester-Young Apr 4 at 13:56

Haskell: 27 (21) characters

It almost feels like cheating to use Haskell for something like this. It just prints Fibonacci numbers ad infinitum.

f=1:scanl(+)1f
main=print f

And if using GHCi only 21 characters, including two newlines, are necessary:

Prelude>let f=1:scanl(+)1f
Prelude>f
[1,1,2,3,5,8,13,21...
share|improve this answer

Javascript, 27 26 characters

for(a=b=1;--n;b+=t)t=a,a=b

In an interactive javascript command line (Like google chrome console) it'll print out the nth fibonacci term for n > 1. undefined for n=1, runs forever for n < 1.

41 characters

for(x=[1,1],y=1;n-++y;)x[y]=x[y-1]+x[y-2]

Saving the n (>=2) first terms in an array.

share|improve this answer

Clojure, 46

(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))

Although, technically 50 since Clojure requires the recur for pseudo tail call:

(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))

Non compressed:

(defn fib [left right iteration]   
  (if (= 0  iteration)
    left
    (fib right (+ right left)  (- iteration 1))))
share|improve this answer

Python 3 (53)

def f(n):
 l,p=0,1
 while n:n,l,p=n-1,p,l+p
 return l
share|improve this answer

C#

Generated as a stream (65 chars):

IEnumerable<int>F(){for(int c=1,s=1;;){s+=c=s-c;yield return c;}}

Could be reduced to 61 characters using non-generic IEnumerable. Of course, if you include the required System.Collections.Generic, then it's a few more characters.

share|improve this answer

Mathematica, 9 chars

Fibonacci

If built-in functions are not allowed, here's an explicit solution:

Mathematica, 33 32 31 chars

#&@@Nest[{+##,#}&@@#&,{0,1},#]&
share|improve this answer
#&@@Nest[{#+#2,#}&@@#&,{0,1},#]& 32 chars. – chyanog Mar 7 at 3:39
@chyanog 31: #&@@Nest[{+##,#}&@@#&,{0,1},#]& – Mr.Wizard Mar 18 at 6:24

J, 10 chars

Using built-in calculation of Taylor series coefficients so maybe little cheaty. Learned it here.

   (%-.-*:)t.

   (%-.-*:)t. 0 1 2 3 4 5 10 100
0 1 1 2 3 5 55 354224848179261915075
share|improve this answer
+1 for looking like a Japanese smiley ^_^ – aditsu Mar 7 at 21:06
@aditsu (q:^-^:p) 6 is 64 729 where p is even. J is probably good for what it does riddles. :) – randomra Mar 7 at 22:54
Even better: (<:^-^:>) 4 is 81 and <:^-^:> 4 is 53.5982. – randomra Mar 7 at 23:21

MATLAB/Octave, n first numbers, 41 39 chars

a=0:1;for(i=3:n);a(i)=a(i-2)+a(i-1);end
share|improve this answer

Javascript - 48 chars

for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}

Clean and simple... probably not a shortness winner :D

Here is the full implementation:

function a(n) {
    var i;
    var f = new Array();
    f[0]=1;

    for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}

    console.log(f);
}
share|improve this answer

Perl - 39 chars

($a,$b)=($b,$a+$b||1),print"$b
"while$=
share|improve this answer

PHP - 109 97 88 49 characters

<?for($a=$b++;;$b+=$a=$b-$a){$s+=$b%2*$b;echo$a;}
share|improve this answer
I have confirmed this works without using the optional parameters, but what exactly are they for? – Kevin Brown Mar 17 '11 at 1:42
@Bass5098: So that the function works when called in a unary context, I presume. If PHP uses JS-style argument passing where you can supply fewer arguments than the function declares, and you can perform meaningful computations involving undefined (or the PHP equivalent thereof), then cool! – Chris Jester-Young Mar 17 '11 at 16:35

Ruby

29 27 25 Chars

p 1,a=b=1;loop{p b=a+a=b}

Edit: made it an infinite loop. ;)

share|improve this answer
8  
did anyone notice b=a+a=b is a palindrome? :) – st0le Jan 28 '11 at 11:11
yes st0le did :) – gnibbler Feb 1 '11 at 12:24
I know I'm late to the party, but can someone explain how the b=a+a=b part works? Can't seem to wrap my head around it. – GigaWatt Feb 7 '12 at 17:58
1  
@GigaWatt, Think of it this way, Instructions are executed left to right...so newb=olda+(a=oldb) – st0le Feb 8 '12 at 5:19
you can save 2 chars by using loop: p 1,a=b=1;loop{p b=a+a=b} – padde Jun 15 '12 at 13:01
show 1 more comment

BrainFuck, 172 characters

>++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]
share|improve this answer

Clojure: 38 chars

    (def f(lazy-cat[0 1](map +(rest f)f)))

run with:

    f
share|improve this answer

PHP, Finite - 46 chars

<?for($b=1;$i++<$n;)echo$b-$a=($b+=$a)-$a,"
";

where $n is the length of the sequence

PHP, Infinite - 39 chars

<?for($b=1;;)echo$b-$a=($b+=$a)-$a,"
";
share|improve this answer

Python (56 chars)

n=input()
x=5**0.5
print ((1+x)**n-(1-x)**n)/((2**n)*x)

And for the sequence

n=input()
i=1
x=5**0.5
while i<=n:
    print ((1+x)**i-(1-x)**i)/((2**i)*x)
    i+=1
share|improve this answer

C / Objective-c, 62

c;f(a,b){printf("%d ",a+b);if(c++<40)f(a+b,a);}main(){f(0,1);}

This will print the first 40 fibonacci numbers. I assume the compiler will set c=0. If it is trash, than it will not work;

This version is smaller, but it infite show all sequence number

C / Objective-c, 50 (infinite)

f(a,b){printf("%d ",a+b);f(a+b,a);}main(){f(0,1);}
share|improve this answer

Perl, 51 (Loopless)

The following code uses Binet's formula to give the Nth Fibonacci number without using any loops.

print((($p=5**.5/2+.5)**($n=<>)-(-1/$p)**$n)/5**.5)
share|improve this answer

Just for fun, a markedly imperative-looking implementation in Haskell, using Lazy ST:

import Control.Monad
import Control.Monad.ST.Lazy
import Data.STRef.Lazy

fibs :: [Integer]
fibs = runST $ do
    ref <- newSTRef (0, 1)
    forM [1,1..] $ \_ -> do
        (a, b) <- readSTRef ref
        writeSTRef ref (b, a + b)
        return a
share|improve this answer

Java, 55

I can't compete with the conciseness of most languages here, but I can offer a substantially different way to calculate the n-th number:

Math.round(Math.pow((Math.sqrt(5)+1)/2,n)/Math.sqrt(5))

n is the input (int or long).

share|improve this answer

C# 4:

Stream (69; 65 if weakly typed to IEnumerable)

(Assuming a using directive for System.Collections.Generic.)

IEnumerable<int>F(){int c=0,n=1;for(;;){yield return c;n+=c;c=n-c;}}

Single value (58)

int F(uint n,int x=0,int y=1){return n<1?x:F(n-1,y,x+y);}
share|improve this answer
2  
Given that n is a uint, n==0 can be shortened to n<1. And the stream can save a few chars by ditching the space after the generic type and declaring x in a wider scope than necessary. In fact, ditch x entirely: n+=c;c=n-c; – Peter Taylor Aug 18 '11 at 11:39
@Peter: Thanks, will edit when I get some time. – Jon Skeet Aug 18 '11 at 12:01
Your single value version is as long as my recursive lambda expression answer...nice! – Andrew Gray Apr 9 at 17:29

Python --

c,f,l=70,0,1;
s='1 ';
for z in range(c):
    n=f+l; f=l; l=n;
    s+=str(n)+' ';
print s;
share|improve this answer
1  
Welcome to CodeGolf.SE! It is customary to put your implementation language and (for code golf, the character count) at the top of you answer, and to use the Markdown facilities to properly format your answer. I'll take care of the code block for you and label this as python. BTW, George's UserScript claims your solution is 89 characters. – dmckee Jun 4 '11 at 17:29
1  
Four suggestions from another python golfer - you don't need the ";" character, the newline serves the same purpose. you can get away with one space not four when you indent your loop. you don't need the spaces or multiple newlines in your loop, n=f+l;f=l;l=n;s+=str(n)+' ' as one line would work just as well. Good luck, I hope to see you around CG.SE! – rmckenzie Jun 4 '11 at 17:35
1 2

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.