115
\$\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\$

238 Answers 238

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\$
  • \$\begingroup\$ You can remove the space between 2 and or \$\endgroup\$ – Cyoce Oct 14 '16 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\$
  • 4
    \$\begingroup\$ actually it's O(log n) since pow has that complexity... \$\endgroup\$ – JBernardo Jul 10 '11 at 2:03
  • 3
    \$\begingroup\$ @JBernado and even bigger since pow for bigint is more complicated story. \$\endgroup\$ – shabunc Aug 19 '11 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\$
  • \$\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 '16 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\$
  • \$\begingroup\$ I have confirmed this works without using the optional parameters, but what exactly are they for? \$\endgroup\$ – Kevin Brown Mar 17 '11 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\$ – Chris Jester-Young Mar 17 '11 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\$

Mathematica,26 chars

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

F# - 42 chars

Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)
\$\endgroup\$
  • \$\begingroup\$ Nice, I didn't know about Seq.unfold! =) \$\endgroup\$ – Roujo Feb 8 '16 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
    \$\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 Piliser Apr 16 '15 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\$ – pawel.boczarski Apr 16 '15 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\$
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\$

R, 33 bytes

CAUTION: This attempts to print the whole Fibonacci sequence. It relies on an overflow of the sequence to stop. On my computer that is around 10^308, so it runs and dies pretty quickly -- throwing an error.

a=1;b=0;while(print(b<-a+b))a=b-a

Pretty simple. Initialize a and b. Then a while loop which adds them to find the next number and print it. Turns out -- two steps after the first numeric overflow, when both a and b are Inf we get NaN or not a number. This gets printed by the print command. But the value it returns is not evaluable by while as true or false (unlike numbers, NaN doesn't have a default logical interpretation), and so the loop throws an error and stops.

Obviously, this pleasant feature relies on about 5 defaults to stop what is otherwise an infinite loop. Works in R 3.2.2

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

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\$
  • 2
    \$\begingroup\$ Welcome to the site! This is a cool answer, I've never heard of the language before. :) \$\endgroup\$ – DJMcMayhem May 4 '17 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\$
  • 2
    \$\begingroup\$ If I'm not mistaken, you don't need to the () around exec in Python 2. \$\endgroup\$ – Stephen Jul 21 '17 at 14:07
  • \$\begingroup\$ @StepHen That seems to be true, thanks, down by 2 chars \$\endgroup\$ – SydB Jul 21 '17 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 '17 at 14:15
2
\$\begingroup\$

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, ' ';
}
\$\endgroup\$
  • \$\begingroup\$ 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! \$\endgroup\$ – Night2 Sep 25 at 9:42
2
\$\begingroup\$

Klein, 23 22 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.

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

Piet, 17 codels

Not sure how to count this one. There are 17 pixels within the code that count as instructions/control flow modifiers (18 if you count the required NOP to get the color back to the correct cycle for the loop).

Shown here at 20 pixels per codel:

Short Fibonacci in Piet

Explanation in pseudocode:

push 1
push 1
push 1
push 1
out (number)
out (number)
START OF INFINITE LOOP
duplicate
push 3
push 1
roll ; the last three instructions amount to "rotate the top to the third spot once"
add
duplicate
out (number)
END OF INFINITE LOOP

This outputs the Fibonacci sequence (starting with 1,1) without delimiters.

Actual image (way too small to see clearly): SMALLER Fibonacci in Piet

\$\endgroup\$
  • \$\begingroup\$ Oh, didn't know there was a convention for this. Was unsure. Will change now. \$\endgroup\$ – Josiah Winslow Sep 13 '17 at 11:29
2
\$\begingroup\$

C, 64 bytes

a,x,y,z=1;main(){for(;;){a=y;y=z;z=a;x+=y;y=x;printf("%d ",x);}}

Try it online! Uses the same method as my Implicit answer.

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

Whitespace, 50 47

Replace S,T,L with Space,Tab,Linefeed:

SSSLSSSTLSLSTLSTLSSSLSLSSTSSTSLTSSSSLSTLSTLSLSL

Explanation:

push 0      SS SL
push 1      SS STL
dup         SLS
outn        TLST
lbl  0      LSS SL
dup         SLS
cpy  2      STS STSL
add         TSSS
dup         SLS
outn        TLST
jmp  0      LSL SL

Outputs all the Fibonacci numbers concatenated (the question didn't mention separating them :)

1123581321345589144233377610987159725844181676510946...

(Thanks to @KevinCruijssen for -3 bytes.)

\$\endgroup\$
  • \$\begingroup\$ Hmmm... When I posted this (the 60th answer), the question automatically became "community wiki" :( \$\endgroup\$ – r.e.s. Dec 2 '13 at 13:48
  • 4
    \$\begingroup\$ Yes, this site automatically community-wikis any posts after the 60th answer. But as a mod, I can undo that, and I'm going through the laborious process of removing community-wiki from all the answers, one by one. :-P \$\endgroup\$ – Chris Jester-Young Dec 2 '13 at 13:56
  • 1
    \$\begingroup\$ I know it's been 4.5 years, but you can golf three bytes by changing SS SSL (push 0) to SS SL (push 0), LSS SSL (label_0) to LSS SL (label_0) and LSL SSL to LSL SL (jump to label_0). Pushing 0 is done implicitly after stating it's either positive/negative, even when you have no S and/or T for the binary part. Try it online (or with just raw spaces/tabs/new-lines: Try it online (47 bytes)). +1 from me, though. Nice answer! \$\endgroup\$ – Kevin Cruijssen Mar 14 '18 at 16:40
  • \$\begingroup\$ @KevinCruijssen - Thanks for the tip. When implementing it, I found and corrected an error that was causing the output to be 01235... instead of the intended 11235.... \$\endgroup\$ – r.e.s. Mar 15 '18 at 3:28
2
\$\begingroup\$

Haskell, 30 bytes (was 33)

f=0:1:[f!!n+f!!(n+1)|n<-[0..]]

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You should add a TIO link and some sample cases \$\endgroup\$ – Muhammad Salman Aug 9 '18 at 19:32
  • \$\begingroup\$ @MuhammadSalman They do not have to add a link. I think "should" is a bit too forceful. \$\endgroup\$ – Jonathan Frech Aug 9 '18 at 19:52
  • \$\begingroup\$ Ok I added the TIO link, this is my first time posting \$\endgroup\$ – mrFoobles Aug 9 '18 at 22:04
  • \$\begingroup\$ @mrFoobles For demonstration purposes, I think main=print f would be more impressive as it shows the magnitude of infinite lists. \$\endgroup\$ – Jonathan Frech Aug 9 '18 at 22:19
  • \$\begingroup\$ @JonathanFrech yeah, should have been you could add and not should add \$\endgroup\$ – Muhammad Salman Aug 10 '18 at 10:28
2
\$\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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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