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:

  • 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.


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\$ Aug 11, 2020 at 11:57
  • \$\begingroup\$ @ChrisJesterYoung can we use 1.0 are 1 only? \$\endgroup\$ May 11, 2022 at 2:45
  • \$\begingroup\$ @NumberBasher 1.0 is fine. \$\endgroup\$ May 20, 2022 at 19:10
  • \$\begingroup\$ What about 1.3? \$\endgroup\$ Aug 28, 2022 at 15:10
  • 2
    \$\begingroup\$ Am I allowed to start the sequence with 0, 1? \$\endgroup\$
    – hakr14
    Oct 11, 2022 at 3:41

336 Answers 336

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

APL(Dyalog Unicode), 16 bytes SBCS

{⊃⊃(+/,⊃)⍤⊢/⍵/1}

Try it on APLgolf!

Straightforward "repeatedly add previous two elements" style approach. Not as short as using pascal's triangle, but I'm still pretty proud of this :-)

-1 thanks to Adám for reminding me of the atop operator, also known as the "atoperator". Also from Adám, an optional "full program" version of this for -2:

⊃⊃(+/,⊃)⍤⊢/⎕/1

Code breakdown:

{⊃⊃(+/,⊃)⍤⊢/⍵/1} full dfn
             ⍵/1  make a list of n 1s
            /      reduce over them with the following tacit function
          ⍤⊢       apply the following tacit function(?) to only the
                   previous element (in js, think (a,b)=>f(a))
    (  , )          return a list of
     +/               sum of elements ([5,3]=>8)
        ⊃             first element ([5,3]=>5)
                      ⍝([5,3]=>[8,5])
                   after the reduce, you're left with
                   a scalar of the value [fib(n),fib(n-1)]
  ⊃                take the first element of this scalar (the array)
 ⊃                 take the first element of the array (this is the end result)

As you can see, I'm still learning how APL works :P

If there are any terminology fixes you want to make in my explanation, go ahead; You have my blessing.

\$\endgroup\$
3
\$\begingroup\$

Seed, 4694 4502 bytes

39 23345386873944734309285705649562214322923535338513787840726059344836991733232701124858784406171983413525769035739193091317312821286862091673034093258254737808529480740867073160694207283540732802589654087348246306424108351751311067631335648365532710947883728455312678903999543414986443810435493370315134647072481870757046559560767136040676281671376819795324434856453735428264762843673716931661746853554648863000837820618766325590788356124601042099541341483064315601051750207795784533758073620813013115058115202328602261019521188162907432705317709462265407997435677959431637608739188384820535674569023665708824769117130584628086812767619300150936306513016713438624735631896208226558553705578499273228365561706607508974248633654644472401969256417949202545503229189330457914013293106347633234904257897628188377211123547522316430704423351649833550317940803484242023657434716958957587230473447472170005697587796499855927956924703860969370032077181183813997697920001129271041258462117064842855557817828287309864524148521039064850419014169734078927801370682493891194692916817142423371375512874755307643229558474820620773013367601053438535142499961672800471263088573030714197841432529737819978024272023115971994335629080760807110601625840500005576870897474597727212673444634680054468191797452281171657965522840129388173724585980135600170025063620602628298627811946062091546889131371926823568681212834659514998682306098670560578318063077703702015608052686405555782215469820110984687203004291914156230320625462064509758167591458209331235212640744714944466265540624319127738893716421169144022527159634296736260757337640921918849758954315864968212488657203226533587353649351778992581839569265033006103790337825946891770665589403131544197363786202809251067880755092540881383788858825619755294045426872602952477879200662412263820311579658891410984567942455376104064634087560919309116469779337448222971714205506106434861563361065264676346668562754032388044586603191705003186050941101737238753507972188516844227916598403811945061789829209022797794856907795280845148337927336190754837895578035971541077446106601429711198909985434167448288125565008326994953358507196336677928811063398215196756813330927829954298340363790942335608247284708980931664255175263323494474655761771711383684020341286483311232450751637188832338282365001980619004736926421020545780168645284628043949398052855672494054844858796879547004560821501647027627620931639915989753539985160519138882067784198444595441811191399424880792691274895217945599103951284792036009843684640644727200173221626567038906492094115422297154223582626065131092394499833564570471955561529154762920901660552470118203300492660926353444889031479441391716424199093929419050805652092712224713014163928963683320445942834620765638299957157761471954992453965174566767052457734421384797861892548612233678879032571407415763995799697084460449481011980933595196444998930307697403672188673825999360332797937744985054511100836407779016165673872373310879592118399300133957780585475517066306666920397584925551254210311998315301028471463539416320653567122160674748915331494295984381121190145666938252633808615711556028673805375510446823318750130981978154654997326727239404525161535622829359058005003740269566983082692378752252198224696254750416200980706704359975518565261545420238758226454680563033057001226125143840414367435620075434502664984902148647078854467653648067041037379150849558209574954581189083630370505506375071080959718696461782683034278484505125465265492405192125616634322283908654348532913099106491870966062276727286614470801650571178850146397543614007581120988735292604484768834605242986004904531743614154630006898576385883749714930636531225280325429278056803694383205579251797535306160456389603169599349989707250713018909969811190663566801819447003975601708056252841800628364818930316430260043879135073603348919031644234002981192629576497660461677947610006543231706577837438811265977164354969644885825582261812180155492583995120383156018469389467006878690072374841382066122175919585112489442594496493463386891710103741087324632245353507660394419350165419526162955982962335197477336304033108148298040661871462588450794544521467248068540365914505422139306015926783904272029251862004795498004645359369772500371366215160030879374914060894959826814924777847813129579229461420328680050563398486579073401384070598971755243256100966805691895631455236232588087146040702221938793149485419052426135144305222421870942178316091451568136489010664122415628294236744095902991276097097917

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 17 characters (17 bytes SBCS)

{({⍵,+/¯2↑⍵}⍣⍵)⍺}

Try it online!

The arguments are the initial sequence on the left, and the number of additional terms to generate on the right. The call can be made shorter by replacing the with 1, but then it can't generate an arbitrary sequence, only the one the question is actually about. Incidentally, replacing the + with a - will produce the other half of the sequence.

As a bonus, the Java answer mentions Binet's formula (with rounding), which I happened to have already written down (23 characters):

{⌊.5+(⍵*⍨+∘÷⍣=⍨1)÷5*.5}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I believe you can use an APL-specific character encoding that would make the characters equal the bytes: codegolf.meta.stackexchange.com/questions/9428/… \$\endgroup\$ Aug 30, 2023 at 13:22
  • \$\begingroup\$ @RydwolfPrograms Thanks! After changing the encoding, the more extensible form of the solution is the same length and so can be at the top, which is great. \$\endgroup\$ Aug 30, 2023 at 16:08
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$
    – The Thonnu
    Aug 30, 2023 at 16:16
2
\$\begingroup\$

Python

a,b,n=0,1,10
while n:a,b,n=b,a+b,n-1;print b
\$\endgroup\$
3
  • 2
    \$\begingroup\$ a=b=1<newline>while 1:print a;a,b=b,a+b 30 Characters \$\endgroup\$
    – st0le
    Feb 1, 2011 at 6:19
  • \$\begingroup\$ @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 :) \$\endgroup\$
    – Mikle
    Nov 24, 2011 at 18:02
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Bakuriu
    Sep 1, 2012 at 9:42
2
\$\begingroup\$

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)
\$\endgroup\$
1
  • \$\begingroup\$ You can remove the space between 2 and or \$\endgroup\$
    – Cyoce
    Oct 14, 2016 at 0:52
2
\$\begingroup\$

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.

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

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)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – Ton Hospel
    Mar 6, 2016 at 13:35
2
\$\begingroup\$

PHP - 109 97 88 49 characters

<?for($a=$b++;;$b+=$a=$b-$a){$s+=$b%2*$b;echo$a;}
\$\endgroup\$
2
  • \$\begingroup\$ I have confirmed this works without using the optional parameters, but what exactly are they for? \$\endgroup\$ Mar 17, 2011 at 1:42
  • \$\begingroup\$ @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! \$\endgroup\$ Mar 17, 2011 at 16:35
2
\$\begingroup\$

Perl - 39 chars

($a,$b)=($b,$a+$b||1),print"$b
"while$=
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Surely, with APL's prodigious operator vocabulary, it should be able to compete in size with the GolfScript one? ;-) \$\endgroup\$ Apr 8, 2013 at 11:32
  • \$\begingroup\$ @ChrisJester-Young Oh probably, but I only started learning APL today... \$\endgroup\$
    – SL2
    Apr 8, 2013 at 23:41
  • \$\begingroup\$ Utilizing Pascal's triangle {+.!∘⌽⍨¯1+⍳⍵} \$\endgroup\$ Apr 8, 2021 at 22:24
2
\$\begingroup\$

Mathematica,26 chars

If[#>1,#0[#-1]+#0[#-2],#]&
\$\endgroup\$
3
  • \$\begingroup\$ Damn, and I just thought I had come up with a new shortest Fibonacci implementation in Mathematica. +1 :) \$\endgroup\$ Jan 30, 2015 at 21:08
  • \$\begingroup\$ What does the trailing & do? \$\endgroup\$
    – Cyoce
    Oct 14, 2016 at 0:55
  • \$\begingroup\$ @Cyoce making it a function, instead of an expression \$\endgroup\$
    – Keyu Gan
    Feb 1, 2018 at 0:40
2
\$\begingroup\$

F# - 42 chars

Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)
\$\endgroup\$
1
  • \$\begingroup\$ Nice, I didn't know about Seq.unfold! =) \$\endgroup\$
    – Roujo
    Feb 8, 2016 at 20:32
2
\$\begingroup\$

JAGL V1.0 - 13 / 11

1d{cdc+dcPd}u

Infinite Fibonacci sequence. Or, if not required to print:

11 bytes

1d{cdc+cd}u
\$\endgroup\$
2
\$\begingroup\$

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.

[a b] x [1 1 ;1 0] equals [a+b a]

, so

[f(1) f(0)] x [1 1 ;1 0]^n equals [f(n+1) f(n)]

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 :).

\$\endgroup\$
2
  • 2
    \$\begingroup\$ I don't think you need the [1 0]. Picking the second item out of the matrix will give you the right number anyway. \$\endgroup\$
    – Andrew
    Apr 16, 2015 at 21:37
  • 2
    \$\begingroup\$ 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). \$\endgroup\$ Apr 16, 2015 at 22:22
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Ruby, 28 bytes

->f{loop{f<<p(f[-1]+f[-2])}}

Usage:

->f{loop{f<<p(f[-1]+f[-2])}}[[-1,1]]
\$\endgroup\$
2
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes (noncompetitive)

Мȫï

Try it here (Firefox only).

More builtins!

math.js + numbers.js = hella functions

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

Try it out here! Or check out the github!

\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Python 2, 43 bytes

def f(n):k=9**n;return k**-~-~n/~-(k*~-k)%k
\$\endgroup\$
2
\$\begingroup\$

Perl 5, 23 bytes

22 bytes, plus 1 for -nE instead of -e.

say$.-=$b+=$.*=-1;redo

Hat tip.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – Deadcode
    Aug 5, 2022 at 19:33
2
\$\begingroup\$

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
)    ;switch to shadowed stack
r    ;standard library call, reverses a stack
     ;stack implicitly printed
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
add
17
17
14
swap
17
17
4
17




11
6
0
0
1
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to the site! This is a cool answer, I've never heard of the language before. :) \$\endgroup\$
    – DJMcMayhem
    May 4, 2017 at 17:29
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

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.

Edit: input() instead of int(raw_input())

\$\endgroup\$
3
  • 2
    \$\begingroup\$ If I'm not mistaken, you don't need to the () around exec in Python 2. \$\endgroup\$
    – Stephen
    Jul 21, 2017 at 14:07
  • \$\begingroup\$ @StepHen That seems to be true, thanks, down by 2 chars \$\endgroup\$
    – SydB
    Jul 21, 2017 at 14:11
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Stephen
    Jul 21, 2017 at 14:15
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.