149
\$\begingroup\$

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, in accordance to the standard rules:

  • Generates the Fibonacci sequence without end.

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

  • Given n calculates the first n terms of the sequence

You may use standard forms of input and output.


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.


Leaderboard

/* 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 ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 3; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

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

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

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

var OVERRIDE_REG = /^Override\s*header:\s*/i;

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

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      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],
        link: a.share_link,
      });
    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;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    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)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

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

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

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

340 Answers 340

1
2
3 4 5
12
6
\$\begingroup\$

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}}
\$\endgroup\$
0
6
\$\begingroup\$

R, 40 bytes

Haven't seen a R solution, so:

f=function(n)ifelse(n<3,1,f(n-1)+f(n-2))
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I know this is an old answer, but you can shorten to 38 bytes \$\endgroup\$
    – Robert S.
    Commented Aug 3, 2018 at 14:53
6
\$\begingroup\$

Cubix, 10 bytes

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

Cubix is a new 2 dimensional language by @ETHproductions were the code is wrapped onto a cube sized to fit.

;.o.ON/+!)

Try it online

This wraps onto a 2 x 2 cube in the following manner

    ; .
    o .
O N / + ! ) . .
. . . . . . . .
    . .
    . .
  • O output the value of the TOS
  • N push newline onto stack
  • / reflect north
  • o output the character of the TOS
  • ; pop TOS
  • / reflect east after going around the cube
  • + add top 2 values of the stack
  • ! skip next command if TOS is 0
  • ) increment the TOS by 1. This kicks off the sequence essentially.

This is an endless loop that prints the sequence with a newline separator. It take advantage of the fact that most commands don't pop the values from the stack.
If the separator is ignored then this can be done with 5 bytes .O+!)

\$\endgroup\$
6
\$\begingroup\$

Common Lisp, 38 bytes

Generates the Fibonacci sequence without end.

(do((a 1 b)(b 1(+ a b)))(())(print a))

Try it online!

The other Common Lisp solution is a function to generate the n-th number. This solution works since in the do loop the assignments to the iteration variables are performed in parallel: so the initialization is equivalent to:

a, b = 1, 1

while at each repetition the assignment is equivalent to:

a, b = b, a+b
\$\endgroup\$
2
  • \$\begingroup\$ Hi sorry is there a way to make it print a certain number of fibonacci numbers? Thanks \$\endgroup\$
    – DialFrost
    Commented Dec 8, 2022 at 2:22
  • \$\begingroup\$ @DialFrost, yes, for instance with this function: (defun f(x)(do((a 1 b)(b 1(+ a b))(i 0 (1+ i)))((= i x)a))). Note that the function is 0-indexed. \$\endgroup\$
    – Renzo
    Commented Dec 8, 2022 at 17:17
6
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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"? \$\endgroup\$
    – Charlim
    Commented Feb 12, 2019 at 19:33
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Stefnotch
    Commented Feb 12, 2019 at 19:40
5
\$\begingroup\$

GolfScript, 13 chars

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

(My answer from a previous Stack Overflow question.)

\$\endgroup\$
5
\$\begingroup\$

JavaScript, 41 39 33 bytes

(c=(a,b)=>alert(a)+c(b,a+b))(0,1)
\$\endgroup\$
2
  • \$\begingroup\$ I don't think the function without the parenthesis is still valid. \$\endgroup\$ Commented Apr 8, 2013 at 16:22
  • \$\begingroup\$ I don't believe this is valid because ES6 came after the challenge was created. Even if it was, you could save a byte by making it a function to return fib(n): f=(n,a=0,b=1)=>n?f(n-1,b,a+b):a; \$\endgroup\$
    – Kade
    Commented Dec 16, 2016 at 14:33
5
\$\begingroup\$

APL (Dyalog Unicode), 7 bytes

This algorithm is based on Pascal's Triangle, and I take no credit for it. Simply submitting it for completeness.

+.!∘⌽⍨⍳

+.! is the summation of binomial coefficients. In this context k!n can be thought of as the kth element in the nth row of Pascal's Triangle (zero indexed).
is the function composition operator called Beside.
reverses the array.
is the commute operator, known as Selfie, it's used to copy the array to the left side of the composed function.
the index generator creates a range, from 0–(n-1) inclusive.

Try it online!

\$\endgroup\$
5
+50
\$\begingroup\$

jq -n, 30 28 bytes

-2 bytes thanks to Michael Chatiskatzi!

Prints the infinite sequence.

[0,1]|while(1;[last,add])[1]

Try it online!

Start with [0,1].
while(1; ... ) infinite loop, 1 is a truthy value.
[last,add] the new pair is the last value of the old pair and the sum of the old pair.
while returns all intermediate pairs, [1] gets the second element of each pair.


jq, 35 33 bytes

A recursive filter written for this tip.

def f:(.<2//[.-1,.-2|f]|add?)//.;

Try it online!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 28 bytes \$\endgroup\$ Commented Sep 10, 2021 at 21:45
  • 1
    \$\begingroup\$ For the record, another 28-byte solution: [1,1]|recurse([last,add])[0] \$\endgroup\$
    – peak
    Commented Jan 28, 2023 at 10:40
5
\$\begingroup\$

Uiua, 12 chars

|1 ⍥ (+,,) ↶ .1

Try It Online!

Explanation:

.1 - repeat last item on stack: essentialy gives 1 1 

↶ unroll - takes your user input (an natural number) and makes it the argument to the repeat

(+,,) - the function to repeat. it take the last two items from the stack, sum them and push to the top

⍥ - repeat modifier, takes the function and number of repeats as arguments

|1 - tells the compiler how many args to take as input

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$
    – rydwolf
    Commented Sep 27, 2023 at 14:55
  • \$\begingroup\$ It's been over 10 months since this was posted, and this is way outdated. The unroll primitive does not exist anymore, and you don't need signatures. You can also use some refactoring to get ◌⍥⊃+∘⊙∩1, which is only 8 characters long. \$\endgroup\$
    – Joao-3
    Commented Aug 1 at 13:42
4
\$\begingroup\$

bc, 36 chars

r=0;l=1;while(i++<99){r+=l;l+=r;r;l}
\$\endgroup\$
4
\$\begingroup\$

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$
\$\endgroup\$
4
  • \$\begingroup\$ Printing out overflowed numbers and/or segfaulting is probably not part of the spec, but nice try. :-) \$\endgroup\$ Commented Apr 4, 2013 at 11:53
  • \$\begingroup\$ 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. \$\endgroup\$
    – Fors
    Commented Apr 4, 2013 at 13:09
  • \$\begingroup\$ Yay! Have an upvote. :-) \$\endgroup\$ Commented Apr 4, 2013 at 13:56
  • \$\begingroup\$ I'm pretty sure you could shave off 2 bytes by replacing if(b>0) with b>0&& and yes, I realize this post is over 4 years old :) \$\endgroup\$ Commented Aug 24, 2017 at 16:29
4
\$\begingroup\$

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;
\$\endgroup\$
5
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Apr 17, 2013 at 18:14
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Apr 17, 2013 at 18:45
  • 1
    \$\begingroup\$ 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: \$\endgroup\$ Commented Apr 17, 2013 at 18:49
  • \$\begingroup\$ Updated to clearly point out our findings. ;) \$\endgroup\$ Commented Apr 17, 2013 at 18:53
  • \$\begingroup\$ 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 \$\endgroup\$
    – Cyoce
    Commented Mar 25, 2016 at 5:59
4
\$\begingroup\$

Windows PowerShell – 34 30

for($b=1){$a,$b=$b,($a+$b)
$a}
\$\endgroup\$
8
  • \$\begingroup\$ 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. \$\endgroup\$
    – Iszi
    Commented Nov 19, 2013 at 17:11
  • \$\begingroup\$ I can even save one more by including the initialisation in the loop header. \$\endgroup\$
    – Joey
    Commented Nov 19, 2013 at 22:13
  • \$\begingroup\$ 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. \$\endgroup\$
    – Iszi
    Commented Nov 27, 2013 at 21:57
  • \$\begingroup\$ 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? \$\endgroup\$
    – Iszi
    Commented Nov 27, 2013 at 22:06
  • \$\begingroup\$ @Iszi, give a separate answer, I guess. It solves a different problem, after all. \$\endgroup\$
    – Joey
    Commented Nov 28, 2013 at 5:55
4
\$\begingroup\$

GNU Octave: 19 chars

@(x)([1,1;1,0]^x)(1)

This solution has the distinction of running in O(log n) time.

\$\endgroup\$
1
  • \$\begingroup\$ Edited it to a language that I can test. \$\endgroup\$ Commented Nov 18, 2015 at 5:43
4
\$\begingroup\$

Cy, 33 31 30 bytes (non-competing)

This is going for the function option (takes N, outputs F(N))

0 1 :>i {1 - $&+ times} &if :<

Ungolfed/explanation:

0 1       # first two fibs are 0, 1
:>i       # read input as integer (let's call it N)
{
  1 -    
    {&+}      # add the last two values
  times     # repeat N-1 times ^
} &if     # if N is non-zero ^
:<        # output the last calculated value (if N is 0, that would be 0)
\$\endgroup\$
4
\$\begingroup\$

Detour (non-competing), 8 bytes

[$<<]!S.

Try it online!

This one is shorter than the word "fibonacci"

[$<<]!S.
Fibonacci

explanation:

[   ]     # while n > 0
 $<<       # replace n with [n-1, n-2]
     !S.  # invert, output




Just for fun, here's one that will always take exactly 19 ticks to terminate, whether given 0 or 1474. On my really old macbook, it on average terminates after 7ms.


Detour, 30 28 bytes

$Q{G<!d}seQ
.{5Vg>d}se-$G_c!

Try it online! This is the way of expressing (((1+sqrt(5))/2)^n-((1-sqrt(5))/2)^n)/sqrt(5)




Old way:


Detour (non-competing), 10 9 bytes

<Q>S.
;$<

Try it online!


This is non-competing: I just pushed the required version of the language about 10 minutes ago.

Detour works like befunge, fish etc. except for one crucial difference: where those languages redirect the instruction pointer, detour redirects data.

Input is pushed in at the beginning of the middle line (in this case the first). < decrements a number, > increments it. Q sends it down if a number is greater than 0, forward otherwise.

the line ;$< is the same as $<; because edges wrap. What it does is take the number it is given, then push that number and 1 less than that number to the input. This is how detour does recursion.

S reduces with addition, and . outputs the result.

For a better explanation, visit the site and it will give a visual representation of all the numbers.

\$\endgroup\$
4
\$\begingroup\$

><>, 11 bytes

10r:n:@+aor

Try it online!

Prints the Fibonacci sequence forever, separated by newlines.

\$\endgroup\$
4
\$\begingroup\$

AsciiDots, 22 21 20 17 16 15 bytes

/.{+}-\
\#$*#1)

Prints the Fibonacci sequence. Outgolfs the sample by 12 13 14 17 18 19 bytes. This is now just 1 byte longer than exactly as long as a simple counter! Try it online!


AsciiDots, 31 30 bytes

 /#$\
.>*[+]
/{+}*
^-#$)
\1#-.

Here's a faster version. It prints out the Fibonacci sequence at a rate of 1 number per 5 ticks, compared to the maximally golfed version's 1 per 8 10 8 12 14 ticks. It's twice as fast as the sample and is still shorter by 3 4 bytes! Try it online!

\$\endgroup\$
4
\$\begingroup\$

05AB1E, 2 bytes

Åf

Try it online!

1-indexed. Built-in.

05AB1E, 2 bytes

λ+

Try it online!

0-index. Non-built-in. As far as I know, this is the first answer using the major 05AB1E rewrite, and uses its newest addition, λ...}, recursive list generation.

How it works

λ+ – Full program.
λ  – Starting from 1, recursively apply a function and collect the results
     in an infinite list.
 + – Addition.
\$\endgroup\$
1
  • \$\begingroup\$ Ah, you beat me to it. \$\endgroup\$
    – Makonede
    Commented Sep 28, 2020 at 16:41
4
\$\begingroup\$

Symbolic Python, 34 31 bytes

-3 bytes thanks to H.PWiz!

__('__=_/_;'+'_,_=_+__,__;_'*_)

Try it online!

Returns the nth element of the Fibonacci, 1-indexed, starting from 1,1,2,3,5....

Explanation:

__(                           ) # Eval as Python code
   '__=_/_;'                    # Set __ to 1
            +'             '*_  # Then repeat input times
              _,_=_+__,__;      # On the first iteration, set _ to __ (1)
                         ;_     # On future iterations, prepend a _
             __,_=_+__,__;      # Set __ to the next fibonacci number
                                # And set _ to the old value of __
                                # Implicitly output _

Or, H.PWiz's version:

__('_=__=_/'+'_;__,_=_+__,_'*_)

Try it online!

Explanation:

__('_=__=_/'+'_;__,_=_+__,_'*_)

__(                           ) # Eval as Python code
   '_=__=_/'+'_;                # Set both _ and __ to 1
             '             '*_  # Repeat input times
                __,_=_+__,__    # Set __ to the next fibonacci number
                                # And set _ to the old value of __
                __,_=_+__,_     # Except on the last iteration
                                # Implicitly output _
\$\endgroup\$
1
  • 2
    \$\begingroup\$ This is possible in 31 bytes. See if you can see how :) \$\endgroup\$
    – H.PWiz
    Commented Dec 17, 2018 at 7:33
4
\$\begingroup\$

Alchemist, 104 87 bytes

-10 bytes thanks to ASCII-only!

_->b+c+m
m+b->m+a+d
m+0b->n
n+c->n+b+d
n+0c->Out_a+Out_" "+o
o+d->o+c
o+0d+a->o
o+0a->m

Produces infinitely many Fibonacci numbers, try it online!

Ungolfed

_ -> b + c + s0

# a,d <- b
s0 +  b -> s0 + a + d
s0 + 0b -> s1

# b,d <- c
s1 +  c -> s1 + b + d
s1 + 0c -> Out_a + Out_" " + s2

# c <- d & clear a
s2 +  d     -> s2 + c
s2 + 0d+  a -> s2
s2     + 0a -> s0

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 95? too lazy to check if algo is shorter \$\endgroup\$
    – ASCII-only
    Commented Jan 29, 2019 at 11:08
  • 1
    \$\begingroup\$ 94 and left sides in better order \$\endgroup\$
    – ASCII-only
    Commented Jan 30, 2019 at 6:29
  • \$\begingroup\$ @ASCII-only: Nice! Noticed I can also output \$\infty\$ many terms, saved another 7 bytes.. but Alchemist indeed needs some work done (atm. it only works when properly killing the process due to some buffering issues). \$\endgroup\$ Commented Jan 31, 2019 at 15:48
  • \$\begingroup\$ lol > bytes bytes \$\endgroup\$
    – ASCII-only
    Commented Jan 31, 2019 at 23:37
4
\$\begingroup\$

Pyramid Scheme, 385 bytes

   ^           ^
  / \         /l\
 /set\       /oop\
^-----^     ^-----^
-    ^-    /]\   ^-^
    ^-    ^---^ ^- -^
   ^-    ^-   -/ \  -^
  ^-     -^   /set\  -^
 /[\     / \ ^-----^  -^
^---^   /out\-    ^-  / \
-^  -^ ^-----^   /+\ /set\
/1\ / \-    /x\ ^---^-----^
---/set\    --- -  /x\   /+\
  ^-----^          ---  ^---^
 /x\   /1\             /x\  -
 ---   ---             ---

Try it online!

This guy's a whopper. Prints terms indefinitely with no separator. The bit on the left initializes the blank variable and x to one, and the bit on the right does the Fibonaccing. The loop condition (everything to the left below loop) prints both variables before checking the blank one for truthiness (it'll always be nonzero). The loop body updates first blank and then x, thus generating the next two terms for the condition to print.

I can't quite figure out set. It doesn't quite follow the chain of execution, but it almost does, I think. I'll be looking at the Pyramid Scheme source in the next few days (and possibly extending the language); perhaps this will provide me with the insight required to golf some bytes off this monstrosity.

\$\endgroup\$
4
\$\begingroup\$

Intel 8087 FPU, 13 bytes

Binary:

00000000: d9e8 d9ee dcc1 d9c9 e2fa df35 c3         ...........5.

Listing:

D9 E8       FLD1                ; push initial 1 into ST(1)
D9 EE       FLDZ                ; push initial 0 into ST
        FIB_LOOP:
DC C1       FADD ST(1), ST      ; ST(1) = ST(1) + ST 
D9 C9       FXCH                ; Exchange ST and ST(1)
E2 FA       LOOP FIB_LOOP       ; loop until n = 0
DF 35       FBSTP [DI]          ; store result as BCD to [DI]
C3          RET                 ; return to caller

As a callable function, input n in CX, output to a 10 byte little-endian packed BCD representation at [DI]. This will compute up to Fibonacci n=87 using the Intel x87 math-coprocessor using 80-bit extended-precision floating point arithmetic.

Run using DOS DEBUG with n = 9, result 34:

enter image description here

n = 87 (0x57), result 679891637638612258:

enter image description here

\$\endgroup\$
4
\$\begingroup\$

Javascript, 27 26 25 23 characters

for(a=b=1;n--;)a+=b=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.

Credit to Bojidar Marinov

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 25: for(b=a=1;n--;)b*=a=1+1/a 23: for(a=b=1;n--;)a+=b=a-b \$\endgroup\$ Commented Sep 25, 2020 at 17:10
4
\$\begingroup\$

convey, 8 bytes

Generates the sequence.

v+"}
1"1

Try it online!

enter image description here

The values (initially 1 and 1) follow the conveyor belts indicated by the arrow heads. " duplicates the input into both outputs, + adds them, and } writes them to the output.

\$\endgroup\$
4
\$\begingroup\$

COBOL (GNU), 170 bytes

I am surprised at the lack of COBOL answers on this site. Well, it is ancient after all.

This outputs the fibonacci sequence correctly up to 38 digits.

PROGRAM-ID.H.DATA DIVISION.LOCAL-STORAGE SECTION.
1 a PIC 9(38).
1 b PIC 9(38).
PROCEDURE DIVISION.G.COMPUTE a=0**b+b -a
ADD a TO b
DISPLAY b(38- FUNCTION LOG10(b):)GO G.

Try it online!

Explanation

We just need two variables, a and b to compute the whole fibonacci sequence. Here is pseudocode of what this would look like:

a = 0
b = 1
loop {
  a = b - a
  b += a
  print(a)
}

Translating the pseudocode above in COBOL is relatively short and simple. But we see that variables in COBOL are set to 0 by default, and having one of them set to a 1 is kind of (8 bytes) long, so we hack it out like so:

a = 0
b = 0
loop {
  a = b - a + 0 ** b
  b += a
  print(b)
}

The 0 ** b ensures that a = 1 on the first iteration. From then on, the logic is the same as in our first pseudocode implementation (since 0 ** (any number greater than 0) = 0). The change from print(a) to print(b) is just to ensure that the numbers are outputted in the correct order.

Ungolfed

PROGRAM-ID. H.

DATA DIVISION.
LOCAL-STORAGE SECTION.
1 a PIC 9(38).                     // Declare a variable named `a` (a = 0)
1 b PIC 9(38).                     // Declare a variable named `b` (b = 0)

PROCEDURE DIVISION.
G.                                 // Define a label named `G`
COMPUTE a=0**b+b -a                // a = b - a + 0 ** b
ADD a TO b                         // b += a
DISPLAY b(38- FUNCTION LOG10(b):)  // Print `b` without trailing zeros
GO G.                              // Jump to the label named `G` (4 lines above)
\$\endgroup\$
2
  • \$\begingroup\$ Hi, I've tried changing 38 to 6 in your code so it prints up to 832040 only, but it seems to continue printing afterwards, any clue why? thx \$\endgroup\$
    – DialFrost
    Commented Dec 13, 2022 at 0:35
  • \$\begingroup\$ The program is an infinite loop, so you would have to exit the loop to stop it from printing. \$\endgroup\$ Commented Dec 13, 2022 at 0:58
4
\$\begingroup\$

Vyxal, 2 bytes

ÞF

Try it Online!

Before you go saying that the online link doesn't match the submission here, that's because the extra , is needed to actually make the output appear online. If you use the offline version, then you will see that the above works just fine. Also, the 5 flag makes sure that the online interpreter times out after 5 seconds.

Explained

ÞF  # Push every Fibonacci number

And now for the non-trivial version

Vyxal 5, 6 bytes

⁽+dk≈Ḟ

Try it Online!

Once again, discrepancies between online link and actual version are for the purposes of making it work online.

Explained

⁽+dk≈Ḟ
⁽+d     # lambda x, y: x + y
   k≈   # the list [0, 1]
     Ḟ  # Create an infinite sequence based on the function and the initial list.

Fun fact: the infinite sequence function you see was inspired by the sequence blocks of the golfing language Arn by ZippyMagician.

\$\endgroup\$
1
  • \$\begingroup\$ Fun fact: I was inspired by Raku when I added sequences \$\endgroup\$ Commented Apr 11, 2021 at 2:36
4
\$\begingroup\$

Halfwit, 5.5 bytes

n><?(:}+

Try It Online!

Halfwit's an experimental golfing language where most commands fit within half a byte. It's stack-based.

n        Push the context variable n, 1 in global scope
 ><      Push an empty compressed integer = 0
   ?(    Input times, do the following...
         Example with stack = [2, 3]
     :   Duplicate [2, 3, 3]
      }  Rotate stack right [3, 2, 3]
       + Add [3, 5]
         And the next pair is now on the stack
         The last one is implicitly output

Here, n(} take up one byte each, and ><?:+ take up half a byte each.

\$\endgroup\$
4
\$\begingroup\$

Quipu, 33 bytes

1&0&\n
[][]/\
^^/\0&
--++??
1&
++

Attempt This Online!

Saved 4 bytes thanks to Jo King.

It prints the Fibonacci sequence separated by newlines.

Equivalent pseudocode:

  a = [0, 0, 0]    // implicitly
0:
  a[0] = a[1] - a[0] + 1
1:
  print a[0]
  a[1] = a[0] + a[1]
2:
  print "\n"
  goto 0
\$\endgroup\$
1
  • \$\begingroup\$ Kaogu. (15chrs) \$\endgroup\$ Commented Apr 15, 2022 at 14:39
1
2
3 4 5
12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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