# 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

## Brainfuck, 22 bytes

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


Generates the Fibonacci sequence gradually moving across the memory tape.

• Beautiful! Litterally beautiful! Or perhaps not... anyways +1 for this :) Aug 18, 2011 at 11:20
• This is 3.344 or 4 bytes in compressed brainfuck. (6 ln(22)) / ln(256) Feb 2, 2016 at 5:12
• 16 bytes: +[[<+>->+>+<<]>] Sep 12, 2016 at 5:19
• 14 bytes: +[.[>+>+<<-]>] Feb 10, 2019 at 20:38
• @Stefnotch of course, the shorter one is destructive. The solution above terminates with the fibonacci sequence on the tape, which is what the 16 byte solution also does. Feb 13, 2019 at 1:30

f=1:scanl(+)1f


Try it online!

• Why not cut two spaces to f=0:scanl(+)1 f? Jan 28, 2011 at 2:27
• Wow, that's even shorter than the usual f@(_:x)=0:1:zipWith(+)f x! Have to remember it. Feb 11, 2011 at 21:10
• You may even strip another space: f=0:scanl(+)1f. Feb 12, 2011 at 17:38

# 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 • I wouldn't even think of ^2 as replacement for 0,1. +1 Jan 3, 2015 at 20:20 • This is no longer valid, you will have to write it as |^2,*+*...*, which is the same number of bytes as 0,1,*+*...*. Nov 8, 2015 at 20:20 • Perl is so weird. Jan 29, 2016 at 5:45 • What version of Perl 6 was this answer written in? Jun 6, 2017 at 22:03 • @CalculatorFeline There was a big change known as GLR (Great List Refactor) which happened shortly before the first official release which was on 2015-12-25. This code would have worked right up until that time. Mar 12, 2018 at 21:30 ## 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);}  • 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; Aug 18, 2011 at 11:39 • @Peter: Thanks, will edit when I get some time. Aug 18, 2011 at 12:01 • Your single value version is as long as my recursive lambda expression answer...nice! Apr 9, 2013 at 17:29 • @wizzwizz4 if I'm not mistaken, if !n works, then so should just n if you flip the conditional. Feb 1, 2018 at 4:07 • @JonSkeet Aw. And here I was thinking I'd beaten Jon Skeet at C#... :-) Feb 1, 2018 at 20:16 ## GolfScript, 12 Now, just 12 characters! 1.{.@.p+.}do  • +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 Jan 29, 2011 at 23:54 • I love a challenge. Done! ;-) Jan 30, 2011 at 0:10 • Nice, you win. At least, until someone makes something even shorter (if that's even possible). :-P Jan 30, 2011 at 0:33 • that definition is almost as short as the name 'Fibonacci' itself! +1 Jun 18, 2012 at 18:21 ## 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  • @aditsu (q:^-^:p) 6 is 64 729 where p is even. J is probably good for what it does riddles. :) Mar 7, 2013 at 22:54 • Even better: (<:^-^:>) 4 is 81 and <:^-^:> 4 is 53.5982. Mar 7, 2013 at 23:21 • The emoji demonstrated here is what all J code should strive towards. On a side note, another alternative is +/@:!&i.- using 9 bytes. Jul 31, 2016 at 4:26 • @miles Very nice! You should post it as it is entirely different from mine. Jul 31, 2016 at 10:21 # Hexagony, 1814 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. 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 • You should link to whatever you used to make the pretty pictures, then put the link on esolangs.org/wiki/Hexagony. Jan 20, 2016 at 22:32 • @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. Jan 20, 2016 at 22:36 • @FryAmTheEggman Impressive! Make it a challenge. I'm sure somebody will post an answer. :D Even better if you could create a website similar to fish's online interpreter. Jan 20, 2016 at 22:37 • @mbomb007 That might be a tad ambitious for a challenge on this site, not to mention it would probably suffer a lot from being really broad. I don't think I will post that, but feel free to do it yourself if you think you have a good way of presenting it. Also, I believe Timwi created a C# ide for hexagony, although I've never used it because I haven't bothered with mono. Jan 20, 2016 at 22:44 • @mbomb007 The ide lives here, by the way, forgot to link it last time. Jan 20, 2016 at 22:51 # Python 2, 34 bytes Python, using recursion... here comes a StackOverflow! def f(i,j):print i;f(j,i+j) f(1,1)  ## ><> - 15 characters 0:nao1v a+@:n:<o  • 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... Mar 18, 2013 at 7:28 • 13 chars: 01r:nao$:@+$r Apr 16, 2015 at 19:25 ## 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  # Jelly, 3 bytes +¡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. # Hexagony, 6 bytes 1.}=+!  Ungolfed:  1 . } = + ! .  It prints the Fibonacci sequence without any separator. • 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. :)) Nov 3, 2015 at 13:19 # Ruby, 29 27 25 24 bytes p a=b=1;loop{b=a+a=p(b)}  Edit: made it an infinite loop. ;) • did anyone notice b=a+a=b is a palindrome? :) Jan 28, 2011 at 11:11 • yes st0le did :) Feb 1, 2011 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. Feb 7, 2012 at 17:58 • @GigaWatt, Think of it this way, Instructions are executed left to right...so newb=olda+(a=oldb) Feb 8, 2012 at 5:19 • On second thought: 22 bytes – G B Jun 17, 2022 at 5:24 # 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.@{.@+}*;  • 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. Mar 31, 2011 at 19:29 # 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. ## 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. • 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, 2011 at 8:17 • I think dc(1) is inherently obfuscated. Jul 30, 2021 at 17:46 Mathematica, 9 chars Fibonacci  If built-in functions are not allowed, here's an explicit solution: Mathematica, 33 32 31 chars #&@@Nest[{+##,#}&@@#&,{0,1},#]&  • #&@@Nest[{#+#2,#}&@@#&,{0,1},#]& 32 chars. Mar 7, 2013 at 3:39 • @chyanog 31: #&@@Nest[{+##,#}&@@#&,{0,1},#]& Mar 18, 2013 at 6:24 • @Mr.Wizard 24 chars (26 bytes): Round[GoldenRatio^#/√5]& Apr 2, 2018 at 4:28 • or 23 chars (27 bytes): Round[((1+√5)/2)^#/√5]& Apr 2, 2018 at 4:56 # 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. ## K - 12 Calculates the n and n-1 Fibonacci number. {x(|+\)/0 1}  Just the nth Fibonacci number. {*x(|+\)/0 1}  • +1 Not bad! If you could shrink it just one character (and provide me a way to test it), I'll accept your answer. :-) Apr 4, 2011 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. Apr 4, 2011 at 16:04 • Could trim a byte by using !2 in place of 0 1: {x(|+\)/!2} Jul 29, 2021 at 18:21 # Julia, 18 bytes n->([1 1;1 0]^n)[]  ## Java, 55 I can't compete with the conciseness of most languages here, but I can offer a substantially different and possibly much faster (constant time) way to calculate the n-th number: Math.floor(Math.pow((Math.sqrt(5)+1)/2,n)/Math.sqrt(5))  n is the input (int or long), starting with n=1. It uses Binet's formula and rounds instead of the subtraction. • I love this solution Mar 27, 2016 at 2:27 • This doesn't seem to work for me, but it's early and I may be missing something! Assuming 0 to be the first number in the sequence, this gives 0, 0, 1, 1, 3, 4, 8, 12, 21, 33 for the first 10 numbers Jun 16, 2017 at 9:28 • @Shaggy Oops! Sorry, I introduced a bug - fixed now. Jun 16, 2017 at 10:06 # Dodos, 26 bytes  dot F F F dip F dip dip  Try it online! ### How it works The function F does all the heavy lifting; it is defined recursively as follows. F(n) = ( F(|n - 1|), F(||n - 1| - 1|) )  Whenever n > 1, we have |n - 1| = n - 1 < n and ||n - 1| - 1| = |n - 1 - 1| = n - 2 < n, so the function returns ( F(n - 1), F(n - 2) ). If n = 0, then |n - 1| = 1 > 0; if n = 1, then ||n - 1| - 1| = |0 - 1| = 1 = 1. In both cases, the attempted recursive calls F(1) raise a Surrender exception, so F(0) returns 0 and F(1) returns 1. For example, F(3) = ( F(1), F(2) ) = ( 1, F(0), F(1) ) = ( 1, 0, 1 ). Finally, the main function is defined as main(n) = sum(F(n))  so it adds up all coordinates of the vector returned by F. For example, main(3) = sum(F(3)) = sum(1, 0, 1) = 2. • I read your README (DODOS) and am super intrigued; it’s a really neat concept! But I can’t find it on Esolangs or anywhere else. Did you come up with it? Apr 2, 2020 at 13:44 # TypeScript's type system, 193188 186 bytes type L='length' type T<N,U extends 0[]=[]>=U[L]extends N?U:T<N,[...U,0]> type S<A,B>=T<A>extends[...infer U,...T<B>]?U[L]:0 type F<N>=N extends 0|1?N:[...T<F<S<N,1>>>,...T<F<S<N,2>>>][L]  There's no way to do I/O here, but we can use hovering to view the value (also note that the generated JS is empty): Unfortunately, TypeScript has strict recursion limits and on F18 we get a Type instantiation is excessively deep and possibly infinite. error: Demo on TypeScript Playground Ungolfed version: type NTuple<N extends number, Tup extends unknown[] = []> = Tup['length'] extends N ? Tup : NTuple<N, [...Tup, unknown]>; type Add<A extends number, B extends number> = [...NTuple<A>, ...NTuple<B>]['length']; type Sub<A extends number, B extends number> = NTuple<A> extends [...(infer Tup), ...NTuple<B>] ? Tup['length'] : never; type Fibonacci<N extends number> = N extends 0 | 1 ? N : Add<Fibonacci<Sub<N, 1>>, Fibonacci<Sub<N, 2>>>;  ## 05AB1E, 7 bytes Code: 1$<FDr+


Try it online!

• Hi, and welcome to PPCG! Nice first post! Jul 5, 2016 at 13:41

## Brainfuck, 16,15, 14/13 chars

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


Generates the Fibonacci sequence and does not print out anything. Also, is shorter than the one above.

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


This one has 14 characters but prints out ASCII characters with the the values of the Fibonacci sequence.

• This is good, but would I be incorrect in saying that the 14 byte version only outputs from the 2nd 1 on? As in "1 2 3 5 8" instead of "1 1 2 3 5 8"? Feb 12, 2019 at 19:33
• @Charlim Oh, you're right. I have no idea what the me of 2014 thought. Anyways, I just fixed it by moving the print instruction to the front of the loop. Feb 12, 2019 at 19:40

# Perl 5, 363533 32 bytes

-2 bytes thanks to dingledooper

1x<>~~/^(..?)*$(??{++$i})/;say$i  Try it online! This works by using the regex ^(..?)*$ to count how many distinct partitions $$\n\$$ has as a sum of the numbers $$\1\$$ and $$\2\$$.

For example, $$\5\$$ can be represented in the following $$\8\$$ ways:

1+1+1+1+1
1+1+1+2
1+1+2+1
1+2+1+1
1+2+2
2+1+1+1
2+1+2
2+2+1


This tells us that the $$\F_5=8\$$.

I had this basic idea on 2014-03-05 but it didn't occur to me until today to try coding it into a program.

The following two paragraphs explain the 33 byte version:

To count the number of distinct matches ^(..?)*$ can make in a string $$\n\$$ characters long, we must force Perl's regex engine to backtrack after every time the regex completes a successful match. Expressions like ^(..?)*$. fail to do what we want, because Perl optimizes away the non-match, not attempting to evaluate the regex even once. But it so happens that it does not optimize away an attempt to match a backreference. So we make it try to match \1. This will always fail, but the regex engine isn't "smart" enough to know this, so it tries each time. (It's actually possible for a backreference to match after $ with the multiline flag disabled, if it captured a zero-length substring. But in this particular regex, that can never happen.) Embedded code is used to count the number of times the regex engine completes a match. This is the (?{++$i}), which increments the variable $i. We then turn it into a non-match after the code block executes. To get this down to 32 bytes, a "postponed" regular subexpression embedded code block is used, $(??{...}) instead of $(?{...}). This not only executes the code, but then compiles that code's return value as a regex subexpression to be matched. Since the return value of ++$i is the new value of $i, this will cause the match to fail and backtrack, since a decimal number (or any non-empty string) will never match at the end of a string. This does make the 32 byte version about 7 times slower than the 33 byte version, because it has to recompile a different decimal number as a regex after each failed match (i.e. the same number of times as the Fibonacci number that the program will output). Using (??{++$i,0}) is almost as fast as (?{++$i})\1, as Perl optimizes the case in which the return value has not changed last time. But that would defeat the purpose of using $(??{...}) in the first place, because it would be 1 byte longer instead of 1 byte shorter.

As to the sequence itself – for golf reasons, the program presented above defines $$\F_0=1,\ F_1=1\$$. To define $$\F_0=0,\ F_1=1\$$ we would need an extra byte:

1x<>~~/^.(..?)*$(??{++$i})/;say$i  Try it online! In the versions below, (?{++$i})\1 is used for speed (at the golf cost of 1 extra byte), to make running the test suite more convenient.

Here it is as a (reasonably) well-behaved anonymous function (47 46 44 bytes):

sub{my$i;1x pop~~/^.(..?)*$(?{--$i})\1/;-$i}


Try it online! - Displays $$\F_0\$$ through $$\F_{31}\$$

The above actually runs faster than the standard recursive approach (39 bytes):

sub f{my$n=pop;$n<2?$n:f($n-2)+f($n-1)}  Try it online! - Displays $$\F_0\$$ through $$\F_{31}\$$ If that is golfed down using Xcali's technique it becomes even slower, at 38 bytes: sub f{"@_"<2?"@_":f("@_"-2)+f("@_"-1)}  Try it online! - Displays $$\F_0\$$ through $$\F_{31}\$$ or with the same indexing as my main answer here, 34 bytes: sub f{"@_"<2||f("@_"-2)+f("@_"-1)}  Try it online! - Displays terms $$\0\$$ through $$\30\$$ See Patience, young "Padovan" for more variations and comparisons. # Perl 5-p, 28 bytes 1x$_~~/^(..?)*$(??{++$\})/}{


Try it online!

I've just learned now, 16 months after posting the main answer above, that Ton Hospel's Sum of combinations with repetition answer used this same basic technique, predating my post by 3 years.

By combining the tricks used in that answer with those already used here, the program length can be reduced even further.

Perl actually literally wraps the program in a loop using string concatenation when called with -p, which I was surprised to learn (I would have implemented it in Perl as an emulated loop). So when this program is wrapped in while (<>) { ... ; print $_} by the -p flag, it becomes: while (<>) {1x$_~~/^(..?)*$(??{++$\})/}{; print $_}  while (<>) implicitly assigns the input from stdin, <>, to $_ (which isn't done when using <> normally) at the beginning of each iteration of its loop.

$\ is the print output terminator. By default it is empty, but the above program turns it into an integer by incrementing it on every possible match found by the regex. If only one number $$\n\$$ is sent to the program via stdin, followed by EOF, then upon exiting the loop $\ will actually represent the $$\n\$$th Fibonacci number.

The while (<>) exits when it encounters EOF, giving $_ an empty value. So then print$_ will print that empty value, followed by the value of $\. As such, it defeats the intended purpose of the -p flag, as this program works properly when given a single value followed by EOF; if given multiple newline delimited values, it will output the sum of those Fibonacci numbers after finally being sent EOF (if running the program interactively, this would be done by pressing Ctrl+D at the beginning of a line). Contrast this with an actually loopable Perl -p program at 37 bytes: 1x$_~~/^(..?)*$(?{++$i})\1/;$i%=$_=$i  Try it online! If the same multiline input is given to the 28 byte program, this happens: Try it online! Sadly, the $\ trick can't be used with say; it only applies to print. The $, variable applies to both print and say, but only comes into play if at least two items are printed, e.g. say"","". • You can convert this to Perl 6 using the ex flag to match all possible combinations. Try it online! – Jo King Apr 16, 2021 at 22:49 • @JoKing Awesome, thanks! I was thinking of looking into Raku, but now I definitely will. Apr 16, 2021 at 23:04 • @JoKing Have you considered defining a SBCS for Raku? It's a shame not to be able to use ∘ as it would save a byte. There are probably plenty of other examples. Apr 17, 2021 at 5:53 • 33 with smartmatch: 1x<>~~/^(..?)*$(?{++$i})\1/;say$i Feb 10, 2022 at 6:57

# K - 8 bytes

+/[;1;0]


## Explanation

It makes use of ngn/k's recurrence builtin.

## How to use

Calculates the nth fibonacci number.

To calculate the nth put the number at the end of the program:

+/[;1;0]40

• Welcome to Code Golf, and nice answer! Oct 25, 2022 at 23:36
• It's annoying how this doesn't seem to be documented. (and hence I have no idea how it works, lol) Oct 26, 2022 at 1:16
• Yeah its not really documented because its specific to ngn/k, but here is something: ngn.codeberg.page/txt/slash.html So it just applies F to the previous two items. And if you use the 4 arg overload, it applies F to every 3 previous elements and so on. hopefully that clears some things up :) Oct 26, 2022 at 1:56
• Ah I see, so the [...;...;] is just a way of providing multiple arguments to +/? The main problem is that the ngn/k documentation isn't very verbose, it just says like one word to say what a function does, so it doesn't make sense often. Oct 26, 2022 at 2:17

## Ruby, 25 chars

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

• Actually you can shorten it even further using a=b=1;loop{p a;b=a+a=b} Apr 4, 2011 at 12:20
• So you st0le his answer? :P Jan 20, 2016 at 22:55

### FAC: Functional APL, 4 characters (!!)

Not mine, therefore posted as community wiki. FAC is a dialect of APL that Hai-Chen Tu apparently suggested as his PhD dissertation in 1985. He later wrote an article together with Alan J. Perlis called "FAC: A Functional APL Language". This dialect of APL uses "lazy arrays" and allow for arrays of infinite length. It defines an operator "iter" (⌼) to allow for compact definition of some recursive sequences.

The monadic ("unary") case of ⌼ is basically Haskell's iterate, and is defined as (F⌼) A ≡ A, (F A), (F (F A)), …. The dyadic ("binary") case is defined somewhat analogously for two variables: A (F⌼) B ≡ A, B, (A F B), (B F (A F B)), …. Why is this useful? Well, as it turns out this is precisely the kind of recurrence the Fibonacci sequence has. In fact, one of the examples given of it is

1+⌼1


producing the familiar sequence 1 1 2 3 5 8 ….

So, there you go, quite possibly the shortest possible Fibonacci implementation in a non-novelty programming language. :D

• Oh, I accidentally un-community-wikied your post as part of my (manual) bulk-unwikiing. Oh well. ;-) Dec 2, 2013 at 13:57

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