Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
2  
To make answers comparable, there schould be just one form of the question, IMHO. – user unknown Apr 12 '11 at 1:29
    
you say "return an infinite number of numbers... or the nth fib within your computer's spec" but I don't understand how a program can do this without having infinite compile- or run-time ? – cat Oct 21 '15 at 16:18
    
For instance, my not-yet-golfed python test will crash python and sometimes my window manager if you request > 2589 fibs or > 1200th fib – cat Oct 21 '15 at 16:19

136 Answers 136

up vote 25 down vote accepted

Perl 6, 10 chars:

Anonymous infinite fibonacci sequence list:

^2,*+*...*

Same as:

0, 1, -> $x, $y { $x + $y } ... Inf;

So, you can assign it to an array:

my @short-fibs = ^2, * + * ... *;

or

my @fibs = 0, 1, -> $x, $y { $x + $y } ... Inf;

And get the first eleven values (from 0 to 10) with:

say @short-fibs[^11];

or with:

say @fibs[^11];

Wait, you can get too the first 50 numbers from anonymous list itself:

say (^2,*+*...*)[^50]

That returns:

0 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 4807526976 7778742049

And some simple benchmark:

real    0m0.966s
user    0m0.842s
sys     0m0.080s

With:

$ time perl6 -e 'say (^2, *+* ... *)[^50]'

EOF

share|improve this answer
    
I wouldn't even think of ^2 as replacement for 0,1. +1 – xfix Jan 3 '15 at 20:20
1  
This is no longer valid, you will have to write it as |^2,*+*...*, which is the same number of bytes as 0,1,*+*...*. – Brad Gilbert b2gills Nov 8 '15 at 20:20
3  
Perl is so weird. – Cyoce Jan 29 at 5:45

Brainfuck, 22 strokes

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

Generates the Fibonacci sequence gradually moving across the memory tape.

share|improve this answer
4  
Beautiful! Litterally beautiful! Or perhaps not... anyways +1 for this :) – Per Hornshøj-Schierbeck Aug 18 '11 at 11:20
    
This is 3.344 or 4 bytes in compressed brainfuck. (6 ln(22)) / ln(256) – Will Sherwood Feb 2 at 5:12
1  
16 bytes: +[[<+>->+>+<<]>] – primo Sep 12 at 5:19

Haskell, 17 15 14 chars

f=0:scanl(+)1f
share|improve this answer
4  
Why not cut two spaces to f=0:scanl(+)1 f? – R. Martinho Fernandes Jan 28 '11 at 2:27
    
@Martinho: Edited, thanks. – Anon. Jan 28 '11 at 2:54
    
Wow, that's even shorter than the usual f@(_:x)=0:1:zipWith(+)f x! Have to remember it. – FUZxxl Feb 11 '11 at 21:10
2  
You may even strip another space: f=0:scanl(+)1f. – FUZxxl Feb 12 '11 at 17:38

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
5  
that definition is almost as short as the name 'Fibonacci' itself! +1 – agent-j Jun 18 '12 at 18:21

C# 4, 58 bytes

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
5  
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
1  
@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 '13 at 17:29
    
codegolf.stackexchange.com/a/44315/110 You can use C# 6 expression bodies to reduce some characters. – Ming-Tang Jul 6 at 1:30

><> - 15 characters

0:nao1v LF a+@:n:<o
share|improve this answer
    
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 '13 at 7:28
3  
13 chars: 01r:nao$:@+$r – randomra Apr 16 '15 at 19:25

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
4  
+1 for looking like a Japanese smiley ^_^ – aditsu Mar 7 '13 at 21:06
2  
@aditsu (q:^-^:p) 6 is 64 729 where p is even. J is probably good for what it does riddles. :) – randomra Mar 7 '13 at 22:54
2  
Even better: (<:^-^:>) 4 is 81 and <:^-^:> 4 is 53.5982. – randomra Mar 7 '13 at 23:21
1  
The emoji demonstrated here is what all J code should strive towards. On a side note, another alternative is +/@:!&i.- using 9 bytes. – miles Jul 31 at 4:26
    
@miles Very nice! You should post it as it is entirely different from mine. – randomra Jul 31 at 10:21

Python, 34

Python, using recursion... here comes a StackOverflow!

def f(i,j):print i;f(j,i+j)
f(1,1)
share|improve this answer

COW, 108

 MoO moO MoO mOo MOO OOM MMM moO moO
 MMM mOo mOo moO MMM mOo MMM moO moO
 MOO MOo mOo MoO moO moo mOo mOo moo
share|improve this answer

Hexagony, 18 14 12

Thanks Martin for 6 bytes!

1="/}.!+/M8;

Expanded:

  1 = "
 / } . !
+ / M 8 ;
 . . . .
  . . .

Try it online


Old, answer. This is being left in because the images and explanation might be helpful to new Hexagony users.

!).={!/"*10;$.[+{]

Expanded:

  ! ) .
 = { ! /
" * 1 0 ;
 $ . [ +
  { ] .

This prints the Fibonacci sequence separated by newlines.

Try it online! Be careful though, the online interpreter doesn't really like infinite output.

Explanation

There are two "subroutines" to this program, each is run by one of the two utilised IPs. The first routine prints newlines, and the second does the Fibonacci calculation and output.

The first subroutine starts on the first line and moves left to right the entire time. It first prints the value at the memory pointer (initialized to zero), and then increments the value at the memory pointer by 1. After the no-op, the IP jumps to the third line which first switches to another memory cell, then prints a newline. Since a newline has a positive value (its value is 10), the code will always jump to the fifth line, next. The fifth line returns the memory pointer to our Fibonacci number and then switches to the other subroutine. When we get back from this subroutine, the IP will jump back to the third line, after executing a no-op.

The second subroutine begins at the top right corner and begins moving Southeast. After a no-op, we are bounced to travel West along the second line. This line prints the current Fibonacci number, before moving the memory pointer to the next location. Then the IP jumps to the fourth line, where it computes the next Fibonacci number using the previous two. It then gives control back to the first subroutine, but when it regains control of the program, it continues until it meets a jump, where it bounces over the mirror that was originally used to point it West, as it returns to the second line.


Preliminary Pretty Pictures!

The left side of the image is the program, the right hand side represents the memory. The blue box is the first IP, and both IPs are pointing at the next instruction to be executed.

enter image description here

Note: Pictures may only appear pretty to people who have similarly limited skill with image editing programs :P I will add at least 2 more iterations so that the use of the * operator becomes more clear.

Note 2: I only saw alephalpha's answer after writing most of this, I figured it was still valuable because of the separation, but the actual Fibonacci parts of our programs are very similar. In addition, this is the smallest Hexagony program that I have seen making use of more than one IP, so I thought it might be good to keep anyway :P

share|improve this answer
    
Nice, I never noticed you posted this. Hexagony (now) takes the value modulo 256 before printing the byte, so *10 can be shortened to M8. I also don't think you need the second IP at all. (I currently have a working version which starts printing from 1 and has the second and fourth line all no-ops... I'll let you know if I manage to move some of those no-ops to the end). – Martin Ender Dec 20 '15 at 19:14
    
Yeah, this works for 16, but I'm sure it's not optimal: )!.!{=/{$/M/8;=+ – Martin Ender Dec 20 '15 at 19:23
    
14: )!{/8;=M/!{M+/ – Martin Ender Dec 20 '15 at 19:28
1  
@mbomb007 I used gimp to manually create each frame, then uploaded the images to some gif making website. Although, several times during this process I considered making a tool to do it, considering how tedious it was. – FryAmTheEggman Jan 20 at 22:36
1  
@mbomb007 The ide lives here, by the way, forgot to link it last time. – FryAmTheEggman Jan 20 at 22:51

Golfscript - single number - 12/11/10

12 chars for taking input from stdin:

~0 1@{.@+}*;

11 chars for input already on the stack:

0 1@{.@+}*;

10 chars for further defining 1 as the 0th Fibonacci number:

1.@{.@+}*;
share|improve this answer
1  
The option is "Calculates, given n, the nth Fibonacci number". So ditch the ~ and you have 11 chars which take n on the stack and leave F_n on the stack. – Peter Taylor Mar 31 '11 at 19:29

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
10  
did anyone notice b=a+a=b is a palindrome? :) – st0le Jan 28 '11 at 11:11
2  
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. – Mr. Llama Feb 7 '12 at 17:58
3  
@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} – Patrick Oscity Jun 15 '12 at 13:01

K - 12

Calculates the n and n-1 Fibonacci number.

{x(|+\)/0 1}

Just the nth Fibonacci number.

{*x(|+\)/0 1}
share|improve this answer
    
+1 Not bad! If you could shrink it just one character (and provide me a way to test it), I'll accept your answer. :-) – Chris Jester-Young Apr 4 '11 at 15:47
    
The only way to shrink it would be to replace the function with a call to a known number: n(|+\)/0 1 Test it using this interpreter. – isawdrones Apr 4 '11 at 16:04

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. – chyaong Mar 7 '13 at 3:39
1  
@chyanog 31: #&@@Nest[{+##,#}&@@#&,{0,1},#]& – Mr.Wizard Mar 18 '13 at 6:24

Hexagony, 6 bytes

Non-competing because the language is newer than the question.

1.}=+!

Ungolfed:

  1 .
 } = +
  ! .

It prints the Fibonacci sequence without any separator.

share|improve this answer
    
This has the minor problem that it doesn't print any separator between the numbers. This isn't entirely well specified in the challenge though. (And I'm really happy someone is using Hexagony. :)) – Martin Ender Nov 3 '15 at 13:19

Jelly, non-competing

3 bytes This answer is non-competing, since it uses a language that postdates the challenge.

+¡1

Try it online!

How it works

+¡1    Niladic link. No implicit input.
       Since the link doesn't start with a nilad, the argument 0 is used.

  1    Yield 1.
+      Add the left and right argument.
 ¡     For reasons‡, read a number n from STDIN.
       Repeatedly call the dyadic link +, updating the right argument with
       the value of the left one, and the left one with the return value.

¡ peeks at the two links to the left. Since there is only one, it has to be the body of the loop. Therefore, a number is read from input. Since there are no command-line arguments, that number is read from STDIN.

share|improve this answer

Prelude, 12 bytes

One of the few challenges where Prelude is actually fairly competitive:

1(v!v)
  ^+^

This requires the Python interpreter which prints values as decimal numbers instead of characters.

Explanation

In Prelude, all lines are executed in parallel, with the instruction pointer traversing columns of the program. Each line has its own stack which is initialised to zero.

1(v!v)
  ^+^
| Push a 1 onto the first stack.
 | Start a loop from here to the closing ).
  | Copy the top value from the first stack to the second and vice-versa.
   | Print the value on the first stack, add the top two numbers on the second stack.
    | Copy the top value from the first stack to the second and vice-versa.

The loop repeats forever, because the first stack will never have a 0 on top.

Note that this starts the Fibonacci sequence from 0.

share|improve this answer

DC (20 bytes)

As a bonus, it's even obfuscated ;)

zzr[dsb+lbrplax]dsax

EDIT: I may point out that it prints all the numbers in the fibonacci sequence, if you wait long enough.

share|improve this answer
11  
I wouldn't call it obfuscated -- obfuscated code is supposed to be difficult to understand, and as far as dc goes the code here is completely straightforward. – Nabb Feb 6 '11 at 8:17

Ruby, 25 chars

st0le's answer shortened.

p 1,a=b=1;loop{p b=a+a=b}
share|improve this answer
6  
Actually you can shorten it even further using a=b=1;loop{p a;b=a+a=b} – Ventero Apr 4 '11 at 12:20
4  
So you st0le his answer? :P – mbomb007 Jan 20 at 22:55

TI-BASIC, 11

By legendary TI-BASIC golfer Kenneth Hammond ("Weregoose"), from this site. Runs in O(1) time, and considers 0 to be the 0th term of the Fibonacci sequence.

int(round(√(.8)cosh(Anssinh‾¹(.5

To use:

2:int(round(√(.8)cosh(Anssinh‾¹(.5
                                     1

12:int(round(√(.8)cosh(Anssinh‾¹(.5
                                     144

How does this work? If you do the math, it turns out that sinh‾¹(.5) is equal to ln φ, so it's a modified version of Binet's formula that rounds down instead of using the (1/φ)^n correction term. The round( (round to 9 decimal places) is needed to prevent rounding errors.

share|improve this answer

GolfScript, 13 chars

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

(My answer from a previous Stack Overflow question.)

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
    
I love this solution – Andreas Mar 27 at 2:27

05AB1E, 7 bytes, non-competing

Code:

1$<FDr+

Try it online!

non-competing because the language i'm using is newer than the challenge.

share|improve this answer
3  
Hi, and welcome to PPCG! Nice first post! – Easterly Irk Jul 5 at 13:41
    
thanks for edit.. So now I got the format... lol – Vimlesh Jul 5 at 15:04
    
Great solution! Unfortunately, this is invalid, since the language you're using is newer than the challenge. You can still keep this answer, though, please mark it as non-competing in the header. – Loovjo Jul 5 at 20:16

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 '13 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 '13 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 '13 at 18:49
    
Updated to clearly point out our findings. ;) – Troy Alford Apr 17 '13 at 18:53
    
Does this handle the F(0)=0 case? It's an easy fix that doesn't cost any extra bytes: just exchange :1 for :n – Cyoce Mar 25 at 5:59

Windows PowerShell – 34 30

for($b=1){$a,$b=$b,($a+$b)
$a}
share|improve this answer
    
You can save 3 by doing away with defining $a at the start (assuming $a is not already defined in the environment), and moving the echo of $a to the end of the loop. – Iszi Nov 19 '13 at 17:11
    
I can even save one more by including the initialisation in the loop header. – Joey Nov 19 '13 at 22:13
    
Wow. I never actually ran this until today for some reason. It's interesting that, past around 1E+308, PowerShell just gives up and calls it Infinity. – Iszi Nov 27 '13 at 21:57
    
I put together a solution, somewhat based on this, that accepts user input and outputs the nth number. Came out to 45 characters. You want that here, or as a separate answer? – Iszi Nov 27 '13 at 22:06
    
@Iszi, give a separate answer, I guess. It solves a different problem, after all. – Joey Nov 28 '13 at 5:55

Desmos, 61 bytes

Golfed

Click the add slider button for n.

p=.5+.5\sqrt{5}
n=0
f=5^{-.5}\left(p^n-\left(-p\right)^{-n}\right)

The last line is the output.

Ungolfed

Is a function.

\phi =\frac{1+\sqrt{5}}{2}
f_{ibonacci}\left(n\right)=\frac{\phi ^n-\left(-\phi \right)^{-n}}{\sqrt{5}}
share|improve this answer
    
+1 for golfing in desmos – Cyoce Oct 13 at 22:10

JavaScript, 41 39 33 bytes

(c=(a,b)=>alert(a)+c(b,a+b))(0,1)
share|improve this answer
    
I don't think the function without the parenthesis is still valid. – Denys Séguret Apr 8 '13 at 16:22

J - 20

First n terms:

(+/@(2&{.),])^:n i.2
share|improve this answer

bash pur, 60 chars

r=0;l=1;for i in {1..40};do((r+=l));((l+=r));echo $r $l;done
share|improve this answer

Common Lisp, 48 Chars

(defun f(n)(if(< n 2) n(+(f(decf n))(f(1- n)))))
share|improve this answer
    
Is left-to-right evaluation order guaranteed in CL? If not, your solution won't work. (There is no such guarantee in Scheme, and many implementations are right-to-left.) – Chris Jester-Young Apr 5 '11 at 2:12
    
Left-to-right is in the standard so since these are all built-in functions it is reliable. (Macros can of course do stupid things :-) – Dr. Pain Apr 29 '11 at 18:00
1  
+1 for clisp use – arrdem Jun 3 '11 at 15:37
    
This is actually 47; you can get rid of the space between (< n 2) and n. – Joshua Taylor Nov 17 '15 at 20:54
    
And a slight modification is 46: (defun f(n)(if(< n 2)n(+(f(1- n))(f(- n 2))))). – Joshua Taylor Nov 17 '15 at 20:55

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.