# Fibonacci function or sequence

The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are both 1. Here are the first few terms:

1 1 2 3 5 8 13 21 34 55 89 ...


Write the shortest code that either:

• Generates the Fibonacci sequence without end.

• Given n calculates the nth term of the sequence. (Either 1 or zero indexed)

You may use standard forms of input and output.

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

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 minimum) has to be supported.

/* Configuration */

var QUESTION_ID = 85; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 3; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});
else console.log(body);
});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();

languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body {
text-align: left !important;
display: block !important;
}

width: 290px;
float: left;
}

#language-list {
width: 290px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• I am sort of waiting for a response like "f", 1 byte, in my math based golf language. Aug 11, 2020 at 11:57
• @ChrisJesterYoung can we use 1.0 are 1 only? May 11, 2022 at 2:45
• @NumberBasher 1.0 is fine. May 20, 2022 at 19:10
• What about 1.3? Aug 28, 2022 at 15:10
• Am I allowed to start the sequence with 0, 1? Oct 11, 2022 at 3:41

# Desmos, 41 bytes

### Code in ticker:

l->join(l,l[L]+l[L-1])


### Code not in ticker

l=[1,1]
L=l.length


Try it online

## Python

a,b,n=0,1,10
while n:a,b,n=b,a+b,n-1;print b

• a=b=1<newline>while 1:print a;a,b=b,a+b 30 Characters Feb 1, 2011 at 6:19
• @st0le that's actually 31 characters. I've spent like 5 minutes recounting my solution, which is identical to yours, until I came to the conclusion you are wrong :) Nov 24, 2011 at 18:02
• The fibonacci sequence starts with 0. So you can't do a=b=1. It should be something like a,b=0,1\nwhile 1:print a;a,b=b,a+b which is 33 characters. Sep 1, 2012 at 9:42

Python, 34 chars first variant, 31 chars for second variant,

a,b=1,1
while 1:print a;a,b=b,a+b


Second variant:

f=lambda x:x<2 or f(x-2)+f(x-1)

• You can remove the space between 2 and or Oct 14, 2016 at 0:52

## Python O(1) Nth number, 91 char

48 characters for the import, a newline, 42 for the rest. I know it's longer than most here and that the question is a bit old, but I looked through the answers and I didn't see any that use the constant-time floating-point calculation.

from math import trunc as t,pow as p,sqrt as s
r=s(5);i=(1+r)/2;f=lambda n:t(p(i,n)/r+.5)


From there you call f(n) for the nth number in the sequence. Eventually it loses precision, and is only accurate up through f(70) (190,392,490,709,135). i is the constant Phi.

• actually it's O(log n) since pow has that complexity... Jul 10, 2011 at 2:03
• @JBernado and even bigger since pow for bigint is more complicated story. Aug 19, 2011 at 8:49

## 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)

• The second term starts small and only becomers smaller later on, so it can always be replaced by integer rounding. Golfing that a bit gives 30 byes: say.5+(.5+5**.5/2)**<>/5**.5|0 Mar 6, 2016 at 13:35

## PHP - 1099788 49 characters

<?for($a=$b++;;$b+=$a=$b-$a){$s+=$b%2*$b;echo$a;}

• I have confirmed this works without using the optional parameters, but what exactly are they for? Mar 17, 2011 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! Mar 17, 2011 at 16:35

Perl - 39 chars

($a,$b)=($b,$a+$b||1),print"$b
"while$=  # 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. # 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  • Surely, with APL's prodigious operator vocabulary, it should be able to compete in size with the GolfScript one? ;-) Apr 8, 2013 at 11:32 • @ChrisJester-Young Oh probably, but I only started learning APL today... – SL2 Apr 8, 2013 at 23:41 • Utilizing Pascal's triangle {+.!∘⌽⍨¯1+⍳⍵} Apr 8, 2021 at 22:24 Mathematica,26 chars If[#>1,#0[#-1]+#0[#-2],#]&  • Damn, and I just thought I had come up with a new shortest Fibonacci implementation in Mathematica. +1 :) Jan 30, 2015 at 21:08 • What does the trailing & do? Oct 14, 2016 at 0:55 • @Cyoce making it a function, instead of an expression Feb 1, 2018 at 0:40 ## F# - 42 chars Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)  • Nice, I didn't know about Seq.unfold! =) Feb 8, 2016 at 20:32 # JAGL V1.0 - 13 / 11 1d{cdc+dcPd}u  Infinite Fibonacci sequence. Or, if not required to print: 11 bytes 1d{cdc+cd}u  # Octave, 26 chars f=@(n)([1 0]*[1 1;1 0]^n)(2)  Basically, a copy of my solution from Calculating (3 + sqrt(5))^n exactly. , so It's a disaster to do unnecessary* loops in Octave/Matlab. It's neither elegant, nor fast, let alone golfy. *All loops that can be vectorized are unnecessary :). • I don't think you need the [1 0]. Picking the second item out of the matrix will give you the right number anyway. Apr 16, 2015 at 21:37 • Thank you for notice, f=@(n)([1 1;1 0]^n)(3) is six characters shorter indeed (Octave enumerates items in matrix top-down and then left-right when indexing with a single number, so the value at first row, second index is at index 3). Apr 16, 2015 at 22:22 # ArnoldC, 451 bytes IT'S SHOWTIME HEY CHRISTMAS TREE a YOU SET US UP 1 HEY CHRISTMAS TREE b YOU SET US UP 1 HEY CHRISTMAS TREE c YOU SET US UP 1 STICK AROUND c TALK TO THE HAND a GET TO THE CHOPPER a HERE IS MY INVITATION a GET UP b ENOUGH TALK TALK TO THE HAND b GET TO THE CHOPPER b HERE IS MY INVITATION b GET UP a ENOUGH TALK GET TO THE CHOPPER c HERE IS MY INVITATION 1e300 LET OFF SOME STEAM BENNET a ENOUGH TALK CHILL YOU HAVE BEEN TERMINATED  This is actually my first ArnoldC program. Horrible for golfing, but great for lolz! Produces an stream of Fibonacci numbers up to 1.1253474885494065e+274. ## Explanation IT'S SHOWTIME #start program HEY CHRISTMAS TREE a #declare a... YOU SET US UP 1 #and set it to 1 HEY CHRISTMAS TREE b #declare b... YOU SET US UP 1 #and set it to 1 HEY CHRISTMAS TREE c #declare c... YOU SET US UP 1 #and set it to 1 STICK AROUND c #while c is truthy TALK TO THE HAND a #output a GET TO THE CHOPPER a #assign a to... HERE IS MY INVITATION a #a... GET UP b #plus b ENOUGH TALK #end assignment TALK TO THE HAND b #output b GET TO THE CHOPPER b #assign b to... HERE IS MY INVITATION b #b... GET UP a #plus a ENOUGH TALK #end assignment GET TO THE CHOPPER c #assign c to... HERE IS MY INVITATION 1e300 #whether 1e300... LET OFF SOME STEAM BENNET a #is greater than a (returns 0 or 1) ENOUGH TALK #end assignment CHILL #end while YOU HAVE BEEN TERMINATED #end program  # Ruby, 28 bytes ->f{loop{f<<p(f[-1]+f[-2])}}  Usage: ->f{loop{f<<p(f[-1]+f[-2])}}[[-1,1]]  # 𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes (noncompetitive) Мȫï  Try it here (Firefox only). More builtins! math.js + numbers.js = hella functions # PARI/GP, 9 bytes fibonacci  Alternate solution (21 bytes), for those disliking the built-in: n->([1,1;1,0]^n)[1,2]  Alternate alternate solution (21 bytes): n->imag(quadgen(5)^n)  I also posted all three solutions (in ungolfed form) to Rosetta Code's Fibonacci page. # Reng v.2.1, 18 bytes (Noncompeting, postdates question) 11{:nAo}#xxx:)+x5h  11 initializes the stack with 2 1s. {:nAo}#x sets the command x to mean "duplicate and output as number" (:n) then "output a newline" (Ao, A = 10). Then, xx prints the initial 2 1s. : duplicates the TOS and ) rotates the stack, so it becomes b a b. + adds the two figures, making it b (a+b). x prints and leaves this new result on the stack. 5h jumps back 5 spaces, and the loop continues. # Fuzzy Octo Guacamole, 11 bytes 01(!aZrZo;)  This takes the infinite route. Explanation: 01 pushes 0 and then 1 to the stack. ( starts a infinite loop. ! sets the register, saving the value on the top of the stack and storing it. It doesn't pop though. a adds the 2 values. ZrZ reverses the stack, pushes the register contents, and reverses again. This pushes the stored number to the bottom of the stack. o; peeks and prints. ) ends the infinite loop. Then the whole things starts again from the (. As a a side note, this is quite fast to hit the max long size possible in Python. The last number it prints is 12200160415121876738, and it repeats that forever. # Python 2, 43 bytes def f(n):k=9**n;return k**-~-~n/~-(k*~-k)%k  # Perl 5, 23 bytes 22 bytes, plus 1 for -nE instead of -e. say$.-=$b+=$.*=-1;redo


Hat tip.

• Is there an old version of Perl in which this worked? Because when I try it, it just outputs -1 repeatedly in a tight loop. Also I don't understand the hat tip; there appears to be nothing related on the linked page, and it says last edited in 2007 (and has the same contents in the Wayback Machine), so it won't have changed since your post. Aug 5, 2022 at 19:33

# Cylon (Non-Competing), 12 bytes

The language is in development, Im just putting this up here.

1:øÌ[:ì+Á])r


An explanation:

1    ;pushes a 1 to the stack
:    ;duplicates the top of the stack
ø    ;reads a number from stdin, pushing it to the stack
Ì    ;non-pushing loop, doesn't push counter to the stack, but deletes it
[    ;start of function, to be pushed to the stack
:  ;duplicate top of stack
ì  ;rotate the stack, moving the copy to the back
+  ;replaces top two objects on the stack with their sum
Á  ;push the result to the shadowing stack (non-consuming)
]    ;end of function
r    ;standard library call, reverses a stack
;stack implicitly printed


# bc, 21

for(b=1;b=a+(a=b);)a


The trailing newline is significant.

Outputs the entire sequence. bc has arbitrary precision arithmetic, so this continues forever.

# OIL, 46 bytes

This program writes an infinite unstoppable stream of fibonacci numbers. It is mostly copied from the standard library but fit to the requirements and golfed.

14
17
17
14
swap
17
17
4
17

11
6
0
0
1

• Welcome to the site! This is a cool answer, I've never heard of the language before. :) May 4, 2017 at 17:29

# Python 2, 30 bytes

f=lambda n:n<3or f(n-2)+f(n-1)


Try it online!

One catch: this outputs True instead of 1. This is allowed by this meta consensus.

# Gaia, 6 bytes

0₁@+₌ₓ


I might make a built-in for this in the future, but built-ins are boring anyway.

### Explanation

0₁      Push 0 and 1
@     Push an input
+₌ₓ  Add the top two stack elements, without popping them, (input) times
Implicitly print the top stack element.


# Python 2, 49 40 chars

a,b=0,1
exec"a,b=b,b+a;"*input()
print b


### Function form, 44 chars

def f(n):a,b=0,1;exec"a,b=b,b+a;"*n;return b


My take on this challenge. Didn't find this kind of an answer yet. I hope it's a valid one.

Print's n:th Fibonacci number. Functions by multiplying the string inside exec n times and then executing it as Python.

• If I'm not mistaken, you don't need to the () around exec in Python 2. Jul 21, 2017 at 14:07
• @StepHen That seems to be true, thanks, down by 2 chars
– SydB
Jul 21, 2017 at 14:11
• Oh, I almost forgot: this would be considered a snippet because it preassumes the value of n. Generally you must write either a full program that gets input, or a function. So, you would have to replace n with input(). See this meta post for more information. Jul 21, 2017 at 14:15

# PHP, 39 bytes

<?php for($b=1;;)echo$a=-$a+$b+=$a,' ';  Try it online! Explanation <?php  An infinite loop is started. The zero-th term in the series, initially $a, is 0, so needn't be assigned. $b is initially the second term and so is set to 1. for ($b = 1;;)


The part which does all the work is echo $a = -$a + $b +=$a, ' ';. Here it is expanded.

{


Calculate the new value for $b: the next term is the sum of the previous two. $b = $b +$a;


$a needs to be moved on one term as well. It is calculated by subtracting itself from the new value of $b.

    $a =$b - $a;  For byte-saving convenience, it is$a that is echoed each time—followed by a space!

    echo $a, ' '; }  • This can be 31 bytes since you don't need PHP's opening tag (you can run with php -r "code here" without opening tag) and you can use _ as separator instead of space: Try it online! Sep 25, 2019 at 9:42 # Klein, 2322 21 + 3 = 24 bytes (non-competing) Run with the 000 topology (1)\((@ ):?\1-+(:(+)$


## Explanation

When the program starts it executes (1) which will put a 1 under the input. It then deflects into the main loop.

The main loop is on the second line. It starts with the \ character. Unwrapped it looks like:

\1-+(:(+)\$):?


This will redirect our pointer if the counter is zero or perform one iteration of the fibonacci sequence otherwise.

Once the counter reaches zero we are deflected to the code ((@, this will hide the top two values (the counter and one of the fibonacci numbers) and terminate the program.

# Chip-8, 36 bytes

6301 'LD v3,1
6D05 'LD vD,5
6E0A 'LD vE,A
A200 'LD I,200
F333 'LDD [I],v3
8343 'XOR v3,v4
8433 'XOR v4,v3
8343 'XOR v3,v4
F265 'LD v2,[I]
F029 'LDF I,v0
00E0 'CLS
DFF5 'DRW vF,vF,5
F129 'LDF I,v1
DDF5 'DRW vD,vF,5
F229 'LDF I,v2
DEF5 'DRW vE,vF,5
1206 'JMP 206


Displays Fibonacci numbers (up to 233) in decimal. (It might be shorter to use hexadecimal, but I think that's cheating)

This one writes the numbers into memory:

6001
A300
8014
F055
8013
8103
8013
1204


... but it's actually longer than valid numbers it writes:

01 01
02 03
05 08
0D 15
22 37
59 90
E9 79 (overflow)