Fibonacci function or sequence

116

16

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>

Chris Jester-Young

Posted 2011-01-28T01:49:09.830

Reputation: 4 464

Answers

48

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

Marco Aurélio da Silva

Posted 2011-01-28T01:49:09.830

Reputation: 596

I wouldn't even think of ^2 as replacement for 0,1. +1 – Konrad Borowski – 2015-01-03T20:20:46.810

2This is no longer valid, you will have to write it as |^2,*+*...*, which is the same number of bytes as 0,1,*+*...*. – Brad Gilbert b2gills – 2015-11-08T20:20:05.360

5Perl is so weird. – Cyoce – 2016-01-29T05:45:00.000

1What version of Perl 6 was this answer written in? – CalculatorFeline – 2017-06-06T22:03:12.210

3@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. – Brad Gilbert b2gills – 2018-03-12T21:30:49.793

time perl6 -e 'say (|^2, *+* ... *)[^50]' now reports 0.224s user time with the current version. – Brad Gilbert b2gills – 2018-03-12T21:32:33.470

@BradGilbertb2gills maybe Marco should change the title to "Perl 6 release candidate 1.2.3", but if a spec and interpreter were ever published for it then it's a valid language for PPCG. – Sparr – 2018-08-10T01:36:07.923

73

Brainfuck, 22 strokes

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

Generates the Fibonacci sequence gradually moving across the memory tape.

R. Martinho Fernandes

Posted 2011-01-28T01:49:09.830

Reputation: 2 135

2This is 3.344 or 4 bytes in compressed brainfuck. (6 ln(22)) / ln(256) – Will Sherwood – 2016-02-02T05:12:10.987

2416 bytes: +[[<+>->+>+<<]>] – primo – 2016-09-12T05:19:16.640

@WillSherwood wouldn't it be 22*ln(6)/ln(256) = 7.1 => 8 instead? – ArBo – 2019-01-10T22:02:58.833

314 bytes: +[.[>+>+<<-]>] – Charlim – 2019-02-10T20:38:41.307

@Charlim I came up with a 14 byte solution back in 2014. https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/42443#42443

– Stefnotch – 2019-02-12T18:14:22.800

@primo Since you came up with a nice and short 16 bytes solution in 2016, I figured you'd be interested in my 14 bytes solution from the year 2014. (Which prints the characters instead of leaving them in the memory tape) – Stefnotch – 2019-02-12T18:16:31.983

2@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. – primo – 2019-02-13T01:30:16.560

5Beautiful! Litterally beautiful! Or perhaps not... anyways +1 for this :) – Per Hornshøj-Schierbeck – 2011-08-18T11:20:51.643

51

Haskell, 17 15 14 chars

f=1:scanl(+)1f

Try it online!

Anon.

Posted 2011-01-28T01:49:09.830

Reputation: 1 799

4Why not cut two spaces to f=0:scanl(+)1 f? – R. Martinho Fernandes – 2011-01-28T02:27:50.983

@Martinho: Edited, thanks. – Anon. – 2011-01-28T02:54:36.290

Wow, that's even shorter than the usual f@(_:x)=0:1:zipWith(+)f x! Have to remember it. – FUZxxl – 2011-02-11T21:10:05.853

4You may even strip another space: f=0:scanl(+)1f. – FUZxxl – 2011-02-12T17:38:11.950

37

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);}

Jon Skeet

Posted 2011-01-28T01:49:09.830

Reputation: 471

http://codegolf.stackexchange.com/a/44315/110 You can use C# 6 expression bodies to reduce some characters. – Ming-Tang – 2016-07-06T01:30:43.017

Your single value version is as long as my recursive lambda expression answer...nice! – Andrew Gray – 2013-04-09T17:29:37.200

@PeterTaylor Can be golfed even more to !n, methinks. – wizzwizz4 – 2017-01-01T12:08:34.277

@Ming-Tang int F(uint n,int x=0,int y=1)=>n<1?x:F(n-1,y,x+y); Although it does state C# 4... – TheLethalCoder – 2017-02-07T17:22:01.793

1@wizzwizz4 if I'm not mistaken, if !n works, then so should just n if you flip the conditional. – Cyoce – 2018-02-01T04:07:42.327

@Cyoce So, you're saying int F(uint n,int x=0,int y=1){return n?F(n-1,y,x+y):x;}? – wizzwizz4 – 2018-02-01T20:07:41.243

@wizzwizz4: Not in C#. n is a uint, not a bool, and the type of the first operand of the conditional ?: operator has to be convertible to bool. – Jon Skeet – 2018-02-01T20:10:27.563

4@JonSkeet Aw. And here I was thinking I'd beaten Jon Skeet at C#... :-) – wizzwizz4 – 2018-02-01T20:16:34.173

@JonSkeet your first one is actually 68 bytes long, there's a trailing new line at the end. – Embodiment of Ignorance – 2019-02-07T23:14:40.503

6Given 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; – Peter Taylor – 2011-08-18T11:39:18.493

1@Peter: Thanks, will edit when I get some time. – Jon Skeet – 2011-08-18T12:01:22.927

32

GolfScript, 12

Now, just 12 characters!

1.{.@.p+.}do

jtjacques

Posted 2011-01-28T01:49:09.830

Reputation: 1 055

5that definition is almost as short as the name 'Fibonacci' itself! +1 – agent-j – 2012-06-18T18:21:35.553

+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 – Chris Jester-Young – 2011-01-29T23:54:08.937

1I love a challenge. Done! ;-) – jtjacques – 2011-01-30T00:10:12.603

Nice, you win. At least, until someone makes something even shorter (if that's even possible). :-P – Chris Jester-Young – 2011-01-30T00:33:44.347

23

><> - 15 characters

0:nao1v LF a+@:n:<o

Kevin Brown

Posted 2011-01-28T01:49:09.830

Reputation: 5 756

513 chars: 01r:nao$:@+$r – randomra – 2015-04-16T19:25:07.310

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... – tomsmeding – 2013-03-18T07:28:57.440

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

randomra

Posted 2011-01-28T01:49:09.830

Reputation: 19 909

2@aditsu (q:^-^:p) 6 is 64 729 where p is even. J is probably good for what it does riddles. :) – randomra – 2013-03-07T22:54:44.847

2Even better: (<:^-^:>) 4 is 81 and <:^-^:> 4 is 53.5982. – randomra – 2013-03-07T23:21:56.077

2The emoji demonstrated here is what all J code should strive towards. On a side note, another alternative is +/@:!&i.- using 9 bytes. – miles – 2016-07-31T04:26:47.200

1@miles Very nice! You should post it as it is entirely different from mine. – randomra – 2016-07-31T10:21:59.563

21

Hexagony, 18 14 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.

enter image description here

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

FryAmTheEggman

Posted 2011-01-28T01:49:09.830

Reputation: 16 206

You should link to whatever you used to make the pretty pictures, then put the link on http://esolangs.org/wiki/Hexagony.

– mbomb007 – 2016-01-20T22:32:03.957

1@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. – FryAmTheEggman – 2016-01-20T22:36:20.050

@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. – mbomb007 – 2016-01-20T22:37:35.933

@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. – FryAmTheEggman – 2016-01-20T22:44:36.247

1

@mbomb007 The ide lives here, by the way, forgot to link it last time.

– FryAmTheEggman – 2016-01-20T22:51:05.423

@mbomb007 and Fry: you can use ffmpeg to encode a video from a sequence of PNG images. Supported video output formats include GIF and WEBM. See this Q&A: it's as simple as ffmpeg -i %03d.png output.gif

– Peter Cordes – 2016-12-07T14:57:27.250

18

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

Timtech

Posted 2011-01-28T01:49:09.830

Reputation: 12 038

18

Python 2, 34 bytes

Python, using recursion... here comes a StackOverflow!

def f(i,j):print i;f(j,i+j)
f(1,1)

jtjacques

Posted 2011-01-28T01:49:09.830

Reputation: 1 055

15

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.

Dennis

Posted 2011-01-28T01:49:09.830

Reputation: 196 637

12

Ruby

29 27 25 24 Chars

p a=b=1;loop{b=a+a=p(b)}

Edit: made it an infinite loop. ;)

st0le

Posted 2011-01-28T01:49:09.830

Reputation: 2 002

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. – Mr. Llama – 2012-02-07T17:58:29.207

3@GigaWatt, Think of it this way, Instructions are executed left to right...so newb=olda+(a=oldb) – st0le – 2012-02-08T05:19:33.067

you can save 2 chars by using loop: p 1,a=b=1;loop{p b=a+a=b} – Patrick Oscity – 2012-06-15T13:01:04.750

13did anyone notice b=a+a=b is a palindrome? :) – st0le – 2011-01-28T11:11:42.787

A little late to the party, but you can shave off another byte: p a=b=1;loop{b=a+a=p(b)} – G B – 2016-12-16T10:31:44.333

2yes st0le did :) – gnibbler – 2011-02-01T12:24:31.090

12

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.@{.@+}*;

aaaaaaaaaaaa

Posted 2011-01-28T01:49:09.830

Reputation: 4 365

1The 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. – Peter Taylor – 2011-03-31T19:29:33.407

11

Mathematica, 9 chars

Fibonacci

If built-in functions are not allowed, here's an explicit solution:

Mathematica, 33 32 31 chars

#&@@Nest[{+##,#}&@@#&,{0,1},#]&

celtschk

Posted 2011-01-28T01:49:09.830

Reputation: 4 650

#&@@Nest[{#+#2,#}&@@#&,{0,1},#]& 32 chars. – chyanog – 2013-03-07T03:39:28.467

1@chyanog 31: #&@@Nest[{+##,#}&@@#&,{0,1},#]& – Mr.Wizard – 2013-03-18T06:24:21.857

1@Mr.Wizard 24 chars (26 bytes): Round[GoldenRatio^#/√5]& – JungHwan Min – 2018-04-02T04:28:09.943

1or 23 chars (27 bytes): Round[((1+√5)/2)^#/√5]& – JungHwan Min – 2018-04-02T04:56:12.843

10

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.

Hiato

Posted 2011-01-28T01:49:09.830

Reputation: 731

13I 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 – 2011-02-06T08:17:32.843

10

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.

Martin Ender

Posted 2011-01-28T01:49:09.830

Reputation: 184 808

10

Hexagony, 6 bytes

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

1.}=+!

Ungolfed:

  1 .
 } = +
  ! .

It prints the Fibonacci sequence without any separator.

alephalpha

Posted 2011-01-28T01:49:09.830

Reputation: 23 988

2This 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. :)) – Martin Ender – 2015-11-03T13:19:24.667

9

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.

lirtosiast

Posted 2011-01-28T01:49:09.830

Reputation: 20 331

8

K - 12

Calculates the n and n-1 Fibonacci number.

{x(|+\)/0 1}

Just the nth Fibonacci number.

{*x(|+\)/0 1}

isawdrones

Posted 2011-01-28T01:49:09.830

Reputation: 236

+1 Not bad! If you could shrink it just one character (and provide me a way to test it), I'll accept your answer. :-) – Chris Jester-Young – 2011-04-04T15:47:20.347

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.

– isawdrones – 2011-04-04T16:04:04.340

8

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.

Hans-Peter Störr

Posted 2011-01-28T01:49:09.830

Reputation: 249

I love this solution – Andreas – 2016-03-27T02:27:47.300

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 – Shaggy – 2017-06-16T09:28:02.920

@Shaggy Oops! Sorry, I introduced a bug - fixed now. – Hans-Peter Störr – 2017-06-16T10:06:06.380

7

Julia, 18 bytes

n->([1 1;1 0]^n)[]

Rɪᴋᴇʀ

Posted 2011-01-28T01:49:09.830

Reputation: 7 410

6

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

FireFly

Posted 2011-01-28T01:49:09.830

Reputation: 7 107

Oh, I accidentally un-community-wikied your post as part of my (manual) bulk-unwikiing. Oh well. ;-) – Chris Jester-Young – 2013-12-02T13:57:43.497

6

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.

Dennis

Posted 2011-01-28T01:49:09.830

Reputation: 196 637

6

Ruby, 25 chars

st0le's answer shortened.

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

Matma Rex

Posted 2011-01-28T01:49:09.830

Reputation: 141

6So you st0le his answer? :P – mbomb007 – 2016-01-20T22:55:32.417

6Actually you can shorten it even further using a=b=1;loop{p a;b=a+a=b} – Ventero – 2011-04-04T12:20:53.950

6

R, 40 bytes

Haven't seen a R solution, so:

f=function(n)ifelse(n<3,1,f(n-1)+f(n-2))

plannapus

Posted 2011-01-28T01:49:09.830

Reputation: 8 610

1

I know this is an old answer, but you can shorten to 38 bytes

– Robert S. – 2018-08-03T14:53:03.090

6

05AB1E, 7 bytes

Code:

1$<FDr+

Try it online!

Vimlesh

Posted 2011-01-28T01:49:09.830

Reputation: 61

3Hi, and welcome to PPCG! Nice first post! – Rɪᴋᴇʀ – 2016-07-05T13:41:50.360

5

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.

Stefnotch

Posted 2011-01-28T01:49:09.830

Reputation: 607

1This 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"? – Charlim – 2019-02-12T19:33:32.207

1@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. – Stefnotch – 2019-02-12T19:40:37.450

5

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

Conor O'Brien

Posted 2011-01-28T01:49:09.830

Reputation: 36 228

5

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+!)

MickyT

Posted 2011-01-28T01:49:09.830

Reputation: 11 735

5

GolfScript, 13 chars

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

(My answer from a previous Stack Overflow question.)

Chris Jester-Young

Posted 2011-01-28T01:49:09.830

Reputation: 4 464

4

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;

Troy Alford

Posted 2011-01-28T01:49:09.830

Reputation: 141

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 – Cyoce – 2016-03-25T05:59:55.717

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. – Andrew Gray – 2013-04-17T18:14:27.527

1

Depends on your compiler. :) It does exactly as you say in Visual Studio - but the Mono compiler at http://www.compileonline.com/compile_csharp_online.php runs it perfectly as-is.

– Troy Alford – 2013-04-17T18:45:39.127

1Didn'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: – Andrew Gray – 2013-04-17T18:49:29.970

Updated to clearly point out our findings. ;) – Troy Alford – 2013-04-17T18:53:37.547

4

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!

Alion

Posted 2011-01-28T01:49:09.830

Reputation: 965

4

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!

ბიმო

Posted 2011-01-28T01:49:09.830

Reputation: 15 345

95? too lazy to check if algo is shorter – ASCII-only – 2019-01-29T11:08:22.380

194 and left sides in better order – ASCII-only – 2019-01-30T06:29:38.827

@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). – ბიმო – 2019-01-31T15:48:17.493

lol > bytes bytes – ASCII-only – 2019-01-31T23:37:09.063

4

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 _

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

1This is possible in 31 bytes. See if you can see how :) – H.PWiz – 2018-12-17T07:33:14.340

4

JavaScript, 41 39 33 bytes

(c=(a,b)=>alert(a)+c(b,a+b))(0,1)

aviraldg

Posted 2011-01-28T01:49:09.830

Reputation: 189

I don't think the function without the parenthesis is still valid. – Denys Séguret – 2013-04-08T16:22:25.463

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; – Kade – 2016-12-16T14:33:51.400

4

bc, 36 chars

r=0;l=1;while(i++<99){r+=l;l+=r;r;l}

user unknown

Posted 2011-01-28T01:49:09.830

Reputation: 4 210

4

Windows PowerShell – 34 30

for($b=1){$a,$b=$b,($a+$b)
$a}

Joey

Posted 2011-01-28T01:49:09.830

Reputation: 12 260

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. – Iszi – 2013-11-19T17:11:18.983

I can even save one more by including the initialisation in the loop header. – Joey – 2013-11-19T22:13:35.697

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. – Iszi – 2013-11-27T21:57:42.787

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? – Iszi – 2013-11-27T22:06:43.517

@Iszi, give a separate answer, I guess. It solves a different problem, after all. – Joey – 2013-11-28T05:55:47.920

Thanks. Done.

– Iszi – 2013-11-28T20:10:55.700

@Iszi That's because beyond 1e308 it's no longer representable in a double-precision float – ASCII-only – 2017-07-09T01:57:02.697

@Iszi That's because beyond 1e308 it's no longer representable in a double-precision float – ASCII-only – 2017-07-09T01:57:13.423

4

GNU Octave: 19 chars

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

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

user2958652

Posted 2011-01-28T01:49:09.830

Reputation: 99

Edited it to a language that I can test. – user2958652 – 2015-11-18T05:43:41.687

4

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.

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

4

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)

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

3

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$

Fors

Posted 2011-01-28T01:49:09.830

Reputation: 3 020

Printing out overflowed numbers and/or segfaulting is probably not part of the spec, but nice try. :-) – Chris Jester-Young – 2013-04-04T11:53:09.187

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. – Fors – 2013-04-04T13:09:14.153

Yay! Have an upvote. :-) – Chris Jester-Young – 2013-04-04T13:56:23.377

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 :) – Matheus Avellar – 2017-08-24T16:29:49.777

3

Javascript, 28 Characters

f=n=>(n<=2)?1:f(n-1)+f(n-2);

Try it here!

Spydercrawler

Posted 2011-01-28T01:49:09.830

Reputation: 61

3Welcome to PPCG! How about n<3? And do you really need the parentheses around the inequality? You can probably also omit the semicolon. – Martin Ender – 2017-03-25T19:43:21.600

3

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

Renzo

Posted 2011-01-28T01:49:09.830

Reputation: 2 260

3

Emojicode, 100 bytes

➡️◀️2➕➖1➖2

Try it online!

betseg

Posted 2011-01-28T01:49:09.830

Reputation: 8 493

3

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

Josiah Winslow

Posted 2011-01-28T01:49:09.830

Reputation: 725

Oh, didn't know there was a convention for this. Was unsure. Will change now. – Josiah Winslow – 2017-09-13T11:29:53.910

3

PowerShell: 42 or 75

Find nth Fibonacci number - 42

A spin-off of Joey's answer, this will take user input and output the nth Fibonacci number. This retains some weaknesses also inherent to Joey's original code:

  • Technically off by 1, since it starts the Fibonacci sequence at 1,1 instead of the more proper 0,1.
  • Only valid for Fibonacci numbers which will fit into int32, because this is PowerShell's default type for integers.
  • Example: Due to the int32 limitation, the highest input that will return a valid report is 46 (1,836,311,903) and this is technically the 47th Fibonacci number since zero was skipped.

Golfed:

($b=1)..(read-host)|%{$a,$b=$b,($a+$b)};$a

Un-Golfed & Commented:

# Feed integers, from 1 to a user-input number, into a ForEach-Object loop.
# Initialize $b while we're at it.
($b=1)..(read-host)|%{
    # Using multiple variable assignment...
    # ...current $b is put into new $a, and...
    # ...sum of current $b and current $a are put into new $b.
    $a,$b=$b,($a+$b)
};
# When loop exits, output $a.
$a

# Variable cleanup, not included in golfed code.
rv a,b

List Fibonacci numbers - 75

Another derivative of Joey's answer, but with some improvements:

  • Zero is included in the output, as it should be according to OEIS.
  • Goes up to the maximum Fibonacci number that can be handled as uint64 instead of the default int32. (Highest Fibonacci number in uint64 is 12,200,160,415,121,876,738.)
  • Output stops once the maximum value is reached, instead of looping through 'Infinity' or continuously throwing errors.

Golfed:

for($a,$b=0,1;$a+$b-le[uint64]::MaxValue){$a;$a,$b=$b,[uint64]($a+$b)}$a;$b

Un-Golfed & Commented:

# Start Fibonacci loop.
for
(
    # Begin with $a and $b at zero and one.
    $a,$b=0,1;

    # Continue so long as the sum fits in uint64.
    $a+$b-le[uint64]::MaxValue
)
{
    # Output current $a.
    $a;

    # Using multiple variable assignment...
    # ...current $b becomes new $a, and...
    # ...sum of current $b and current $a is forced to uint64 and stored in new $b.
    $a,$b=$b,[uint64]($a+$b)
}

# Output $a and $b one more time.
$a;$b

# Variable cleanup - not included in golfed code.
rv a,b

Iszi

Posted 2011-01-28T01:49:09.830

Reputation: 2 369

One thing that bugs me a little in PowerShell: Read-Host always reads interactively and won't pick up things you pipe into the script (or process), whereas $input (which is what I tend to use) only picks up piped input (for obvious reasons; that's how it's defined) but cannot be used interactively. Which means that you can write a PowerShell script that either works interactively or one that works with piped input, but not both at the same time (at least not for golfing). – Joey – 2013-11-28T20:21:02.807

Yeah, and I personally prefer my scripts to be interactive whether the challenge calls for it or not. Wait... Did you just golf the un-golfed code? And not just any part of it, but particularly the bit that's not at all in the golfed code? – Iszi – 2013-11-28T22:57:22.590

I merely optimized it, since Remove-Variable takes a string[]. There is no need to have two calls ;-) – Joey – 2013-11-29T06:13:58.083

I meant to say I found it amusing that of all the code to be optimized, you had to go and fix the bit that wasn't even part of the golfed solution. It's like you had an OCD moment or something. – Iszi – 2013-11-29T07:25:06.573

Sometimes I do ;-). I don't see anything that makes the golfed code smaller either. For an algorithm this simple there aren't many options and range|% is often the shortest (but also the slowest) way. – Joey – 2013-11-29T07:27:18.353

3

Lean, 42 35 bytes

7 bytes thanks to Mario Carneiro.

def f:_->nat|(n+2):=f(n+1)+f n|x:=x

Try it online!


Lean is a completely different kind of a programming language: it is a proof-assistant. That means, mathematical theorems can be formalized and proved in Lean, and mathematical objects can be constructed in Lean.

In this case, the auto-generated correctness theorems are (cf tio link):

f.equations._eqn_1 : f 0 = 0
f.equations._eqn_2 : f 1 = 1
f.equations._eqn_3 : ∀ (n : ℕ), f (n + 2) = f (nat.succ n) + f n

Leaky Nun

Posted 2011-01-28T01:49:09.830

Reputation: 45 011

I had no idea anyone else knew about Lean. – qwr – 2018-03-31T17:38:44.610

"else" :o ... are you in the lean chat? – Leaky Nun – 2018-03-31T17:39:33.107

No, but the only reason I know it exists is because I know someone who contributed to it – qwr – 2018-03-31T17:47:30.957

@qwr might I know him? – Leaky Nun – 2018-03-31T17:47:49.333

If you know Jeremy Avigad – qwr – 2018-03-31T17:50:44.320

@qwr I don't talk to him much on the Lean chat, but I've seen this name – Leaky Nun – 2018-03-31T17:51:00.493

Is this a code golf chat or on another site? – qwr – 2018-03-31T17:53:38.980

@qwr it's the official Lean chat https://leanprover.zulipchat.com and has no affiliation with codegolf

– Leaky Nun – 2018-03-31T17:54:14.497

I didn't know that existed, huh. Do you work with or on Lean? I've heard of some theorems being formalized but not much else. – qwr – 2018-03-31T17:59:09.750

@qwr I'm a volunteer that contributes to mathlib, a library of Lean – Leaky Nun – 2018-03-31T18:00:48.640

3

Flobnar, 19 bytes

@\
#_+_1
!_:.
9>$!,

Try it online!

Generates the sequence with no end, separating each number with a tab.


One year later...

I should probably check if I've already answered a question before I start coding...

Anyway, here's an alternative 19 byter that outputs in the same way, only 1-indexed this time and without the leading tab.

Flobnar, 19 bytes

!\$\@
:>+_,9
+ <>$.

Try it online!

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

1+1 for 'I should probably check if I've already answered a question' – EdgyNerd – 2019-08-29T09:00:13.933

3

C++, 42 bytes

I haven't read every solution in this challenge, but the leaderboard doesn't have a C++ solution, which is a travesty.

int f(int i){return i-->1?f(i)+f(i-1):!i;}

Joe

Posted 2011-01-28T01:49:09.830

Reputation: 895

3

bash pur, 49 chars, third solution

r=0;l=1;echo -e {1..45}" $((r+=l)) $((l+=r))\n";

bash pur, 52 chars, second solution

r=0;l=1;echo -e {1..40}" "$((r+=l))" "$((l+=r))\\n;

former solution (60 chars):

r=0;l=1;for i in {1..40};do((r+=l));((l+=r));echo $r $l;done

user unknown

Posted 2011-01-28T01:49:09.830

Reputation: 4 210

Could be written: r=1 l=0;echo -e {,,}{,,}{,,}" $[r+=l] $[l+=r]" – F. Hauri – 2019-02-27T00:08:48.630

... And former version: for((r=1,l=1;l<9**9;r+=l,l+=r)){ echo $r $l;} – F. Hauri – 2019-02-27T00:16:40.830

234 chars: for((a=1;b+=a;a+=b)){ echo $a $b;} – roblogic – 2019-08-28T08:56:36.753

@F.Hauri: My improved solution is only 1 char longer than yours, with preserving the line oriented output, while your solution doesn't reach the max possible value before integer overrun. – user unknown – 2019-08-28T19:27:34.443

1@roblogic: In my opinion, negative results are not acceptable, but with a halting condition like for((a=1;b+=a;a+=b)){ echo $a $b;}|head -n46 your code is still 4 characters shorter than mine (improved one) - so why don't you publish your solution as an answer, or did you? – user unknown – 2019-08-28T19:32:53.147

I published a zsh answer, which I wil have to correct :\ – roblogic – 2019-08-29T00:27:49.440

Ok, I finally posted my (former) version (inspired by your;)

– F. Hauri – 2019-08-29T22:31:15.567

3

Common Lisp, 48 Chars

(defun f(n)(if(< n 2) n(+(f(decf n))(f(1- n)))))

Dr. Pain

Posted 2011-01-28T01:49:09.830

Reputation: 261

This is actually 47; you can get rid of the space between (< n 2) and n. – Joshua Taylor – 2015-11-17T20:54:39.940

And a slight modification is 46: (defun f(n)(if(< n 2)n(+(f(1- n))(f(- n 2))))). – Joshua Taylor – 2015-11-17T20:55:24.777

Is left-to-right evaluation order guaranteed in CL? If not, your solution won't work. (There is no such guarantee in Scheme, and many implementations are right-to-left.) – Chris Jester-Young – 2011-04-05T02:12:42.600

Left-to-right is in the standard so since these are all built-in functions it is reliable. (Macros can of course do stupid things :-) – Dr. Pain – 2011-04-29T18:00:27.827

3

J - 20

First n terms:

(+/@(2&{.),])^:n i.2

Eelvex

Posted 2011-01-28T01:49:09.830

Reputation: 5 204

3

Forth - 38 33 bytes

: f dup . 2dup + 2 pick recurse ;

Generates and prints a Fibonacci series recursively until it runs out of stack space.

Usage:

 1 1 f

Or to generate Fn, where n>=1 (66 bytes):

: f dup 3 < if 1 nip else dup 1- recurse swap 2 - recurse + then ;

Example of usage:

9 f .

output:

34 

Michael

Posted 2011-01-28T01:49:09.830

Reputation: 231

It does work, but like I said it doesn't terminate itself. It should generate correct output up until 46! at least, and after that it will just keep on going and output "garbage". And since that online compiler doesn't appear to have any way of halting the execution without clearing the console output it gets pretty hard to see the correct output at the beginning. – Michael – 2015-10-14T15:23:18.643

So it just runs so fast that all I can see is the zeros? – mbomb007 – 2015-10-14T18:39:54.777

Right. If you run it in Win32Forth you can scroll up and get it to stay at the top so that you actually can see the correct output for Fn up to n=46. – Michael – 2015-10-14T19:37:42.057

Also, if I'm not mistaken : f over . 2dup + recurse ; is shorter (27 bytes). This way, the first number is printed first, and the numbers are in order on the stack, so we don't need 2 pick. – mbomb007 – 2015-10-14T20:19:06.207

Yup, that seems to generate the same sequence as my version. – Michael – 2015-10-14T20:53:20.293

Since you're into Forth, you may find my answer interesting. Since they're completely different from yours, I made my own answer instead of suggesting edits.

– mbomb007 – 2015-10-14T21:07:20.180

3

BrainFuck, 172 characters

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

Credit goes to Daniel Cristofani

Kevin Brown

Posted 2011-01-28T01:49:09.830

Reputation: 5 756

3

Java, 41 bytes

There are a couple other Java answers here, but I'm surprised nobody has posted this simple one:

int f(int n){return n<2?n:f(n-1)+f(n-2);}

For an extra byte you can extend the range up to long.

Geobits

Posted 2011-01-28T01:49:09.830

Reputation: 19 061

3

TeaScript, 4 bytes

F(x)

F(x) //Find the Fibonacci number at the input

Compile online here (DOES NOT WORK IN CHROME). Enter input in the first input field.

user41805

Posted 2011-01-28T01:49:09.830

Reputation: 16 320

6

This entry fails the creating a compiler after a challenge has been posted loophole and therefore isn't valid. I can't accept this answer, sorry.

– Chris Jester-Young – 2015-11-03T19:14:31.027

With TeaScript 3, you can just do . – Downgoat – 2016-01-29T06:03:55.540

3

J, 9 bytes

+/@:!&i.-

Gets the nth Fibonacci number by finding the sums of the binomial coefficients C(n-i-1, i) for i from 0 to n-1.

Also, a short way using 12 bytes to generate the first n Fibonacci numbers is

+/@(!|.)\@i.

It uses the same method as above but works by operating on prefixes of the range [0, 1, ..., n-1].

Usage

   f =: +/@:!&i.-
   f 10
55
   f 17
1597

Explanation

+/@:!&i.- Input: n
        - Negate n
     &i.  Form the ranges [n-1, n-2, ..., 0] and [0, 1, ..., n-1] 
    !     Find the binomial coefficient between each pair of values
+/@:      Sum those binomial coefficients and return

miles

Posted 2011-01-28T01:49:09.830

Reputation: 15 654

Whoa. Just whoa. – Conor O'Brien – 2016-09-24T00:38:07.983

3

Python 33 characters

x,y=0,1
while 1:print x;x,y=y,x+y

This will be an infinite loop!


Python 31 characters

def f(a=[1,0]):a[:]=a[1],sum(a)

demonstration

for _ in range(10):
    f(); print f.func_defaults[0][0]

0
1
1
2
3
5
8
13
21
34

piRSquared

Posted 2011-01-28T01:49:09.830

Reputation: 131

2The loop for your "31 char" program would need to be included in the score. – mbomb007 – 2016-11-04T15:00:15.163

^^ also, we usually give the count in bytes, not characters. – FlipTack – 2016-12-28T12:25:09.357

3

Java, 90 characters and just two variables

There was one before with 55 characters, but it used a variable without declaring it and had no output. This one has both and (the actual logic) is shorter. And as a little bonus it looks absolutely horrific code-style-wise and depends on compiler quirks, yay!

interface A{static void main(String[]x){for(int a,b=a=1;;System.out.println(b=a+(a=b)));}}

The special features I used are:

  • Using an interface instead of a class. The program can still be run as normal, but I don't need to write "public" twice. This saves 10 characters
  • Declaring multiple variables at once: int a,b;
  • Initializing multiple variables at once and in the declaration, needs a second a: b=a=1;
  • Everything is done in the for head, the body is empty: for(...);
    The first and third block of for are intended for variable initialization and variable incrementation, but they can hold any commands.
  • The whole logic is inside the output: System.out.println(b=a+(a=b))
  • Just two variables without recursion! This is done by using the way the compiler works: The assignment to b first reads the value of a, then it evaluates the right side of the +, where it reads the value of b and writes it into a, but the left side of the + still has the old value of a that gets added to the value of b after assigning the value of b to a. Then that sum gets written to b while a already holds the old value of b.
    I was lucky that the compiler works this way, because it could also have first evaluated the expression in the brackets, like for example C does, then it just lists all powers of 2 instead of the Fibonacci numbers.

In a dream programming language this would just be: b=a+(a=b

Fabian Röling

Posted 2011-01-28T01:49:09.830

Reputation: 134

Dammit, referring to this answer just helped me in actually useful code, but I can't upvote it! :D – Fabian Röling – 2019-05-27T21:56:18.713

2

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

tkaden4

Posted 2011-01-28T01:49:09.830

Reputation: 21

2

Mathematica,26 chars

If[#>1,#0[#-1]+#0[#-2],#]&

chyanog

Posted 2011-01-28T01:49:09.830

Reputation: 1 078

Damn, and I just thought I had come up with a new shortest Fibonacci implementation in Mathematica. +1 :) – Martin Ender – 2015-01-30T21:08:11.590

What does the trailing & do? – Cyoce – 2016-10-14T00:55:26.307

@Cyoce making it a function, instead of an expression – Keyu Gan – 2018-02-01T00:40:26.857

2

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.

Christopher Currens

Posted 2011-01-28T01:49:09.830

Reputation: 121

2

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

Laura Bostan

Posted 2011-01-28T01:49:09.830

Reputation: 181

2Welcome to the site! This is a cool answer, I've never heard of the language before. :) – James – 2017-05-04T17:29:04.573

2

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.

Post Rock Garf Hunter

Posted 2011-01-28T01:49:09.830

Reputation: 55 382

2

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.

totallyhuman

Posted 2011-01-28T01:49:09.830

Reputation: 15 378

2

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.

Business Cat

Posted 2011-01-28T01:49:09.830

Reputation: 8 927

2

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

SydB

Posted 2011-01-28T01:49:09.830

Reputation: 31

2If I'm not mistaken, you don't need to the () around exec in Python 2. – Stephen – 2017-07-21T14:07:45.797

@StepHen That seems to be true, thanks, down by 2 chars – SydB – 2017-07-21T14:11:12.340

1

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.

– Stephen – 2017-07-21T14:15:53.853

2

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, ' ';
}

WebSmithery

Posted 2011-01-28T01:49:09.830

Reputation: 221

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!

– Night2 – 2019-09-25T09:42:19.147

2

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.

MD XF

Posted 2011-01-28T01:49:09.830

Reputation: 11 605

61 bytes. – Jonathan Frech – 2018-08-19T04:01:27.283

2

F# - 42 chars

Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)

goric

Posted 2011-01-28T01:49:09.830

Reputation: 271

Nice, I didn't know about Seq.unfold! =) – Roujo – 2016-02-08T20:32:19.270

2

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

r.e.s.

Posted 2011-01-28T01:49:09.830

Reputation: 2 872

Hmmm... When I posted this (the 60th answer), the question automatically became "community wiki" :( – r.e.s. – 2013-12-02T13:48:14.857

4Yes, 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 – Chris Jester-Young – 2013-12-02T13:56:28.790

1

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!

– Kevin Cruijssen – 2018-03-14T16:40:10.200

@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.... – r.e.s. – 2018-03-15T03:28:33.297

2

PHP - 109 97 88 49 characters

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

detour

Posted 2011-01-28T01:49:09.830

Reputation: 21

I have confirmed this works without using the optional parameters, but what exactly are they for? – Kevin Brown – 2011-03-17T01:42:56.427

@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! – Chris Jester-Young – 2011-03-17T16:35:04.987

2

Haskell, 30 bytes (was 33)

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

Try it online!

mrFoobles

Posted 2011-01-28T01:49:09.830

Reputation: 41

You should add a TIO link and some sample cases

– Muhammad Salman – 2018-08-09T19:32:14.893

@MuhammadSalman They do not have to add a link. I think "should" is a bit too forceful. – Jonathan Frech – 2018-08-09T19:52:17.443

Ok I added the TIO link, this is my first time posting – mrFoobles – 2018-08-09T22:04:09.173

@mrFoobles For demonstration purposes, I think main=print f would be more impressive as it shows the magnitude of infinite lists. – Jonathan Frech – 2018-08-09T22:19:59.523

@JonathanFrech yeah, should have been you could add and not should add – Muhammad Salman – 2018-08-10T10:28:39.747

2

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.

Mr. Xcoder

Posted 2011-01-28T01:49:09.830

Reputation: 39 774

2

Prolog, 36 35 29 bytes

X+Y:-writeln(X),Z is X+Y,Y+Z.

Run with 1+1. (I don't think having to call the base case is cheating, but let me know.)

Prints the first parameter and a newline, sets Z to X+Y, then does a recursive call.

Edit 1: Can use writeln(X) instead of write(X),nl, saving one character.

Edit 2: Can use X+Y as a predicate instead of f(X,Y), saving 6 characters. Also the initial call is shorter.

Alex Trotta

Posted 2011-01-28T01:49:09.830

Reputation: 21

2Welcome to PPCG! The usual consensus is to include the function invocation if it needs to be called with special arguments. – Laikoni – 2018-11-04T10:46:09.617

Should I include the call in the character count? – Alex Trotta – 2018-11-04T16:54:48.103

26 bytes: X+Y+O:-O=X;Z is X+Y,Y+Z+O. Try it online!

– ankh-morpork – 2020-02-05T19:18:29.633

2

Alchemist, 68 bytes

y+_->y+a+b
y+0_->z
z+a->z+_
z+0a->x
x+b->x+a
x+0b->y+Out_a+Out_" "!y

Try it online!

Outputs the 1-based sequence infinitely, If you want 0-based (i.e. 0 1 1 2 3 5...), you can change the trailing y to either x or z.

Explanation:

!y              # Initialise the program with the y flag alongside the default _

y+_->y+a+b      # Convert all _ atoms to a and b atoms
y+0_->z         # Once we're out of _ atoms, change to the z flag

z+a->z+_        # Convert the a atoms back to _ atoms
z+0a->x         # Switch to the x flag

x+b->x+a        # Convert all b atoms to a atoms
x+0b->y         # Once we're out, change to y flag
       +Out_a   # Print the number of a atoms
       +Out_" " # And a separator

If it makes you feel better, here's a more pseudo-codey version:

_=1
while true:
    a=a+_
    b=_
    _=a
    a=b
    print a

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

2

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.

Khuldraeseth na'Barya

Posted 2011-01-28T01:49:09.830

Reputation: 2 608

2

Zsh, 31 bytes

try it online

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

32 bytes, based on James Brown's awk solution:
for ((y=1;z=x+y;y=z))echo $[x=y]

42 bytes, to halt before int overflow:
(for ((a=1;b+=a;a+=b))echo $a $b)|head -46

NB: For a properly "endless" solution I need logic for long long (..) long integers, per this post

roblogic

Posted 2011-01-28T01:49:09.830

Reputation: 554

2

pure bash, 43 chars

Inspired from user unknown's answer:

for((r=l=i=1;i++<40;l+=r+=l)){ echo $r $l;}

Not really golfed, but I like it anyway.

Or

r=1 l=0;echo {,,}{,,}{,,}\ $[r+=l]\ $[l+=r]

F. Hauri

Posted 2011-01-28T01:49:09.830

Reputation: 2 654

2

Cascade, 28 25 bytes

?01
^/ 
|.#
!9]
-0
!0]
+1

Try it online!

Outputs the Fibonacci numbers separated by tabs starting from 1. This shows off the behaviour of variables in Cascade, in that the variables 1 and 0 aren't static in this program.

Unfolded, this looks something like:

     @
     ^
    ^ \
   / . |
  #  9 |
  ]    |
 0 -   |
  ] 0  |
 1 +   /
  1 0 /
     |

Try it online!

This initially branches twice, with the leftmost going down the tree until it sets ([) the variable 1 to the sum (+) of 1 and 0. Then it sets 0 to that value to the result of that minus 0. This has the effect of advancing one element in the Fibonacci sequence.For example, the values of repeated executions are:

0 1
1 1
1 2
2 3
3 5
5 8
8 13
...

Finally it prints the total result of that, which is the new value of 0. The next branch prints the tab separator (.9), and the final branch loops back around to the top of the program.

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

2

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)

eordano

Posted 2011-01-28T01:49:09.830

Reputation: 161

You can remove the space between 2 and or – Cyoce – 2016-10-14T00:52:27.750

2

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.

Joel B Fant

Posted 2011-01-28T01:49:09.830

Reputation: 121

4actually it's O(log n) since pow has that complexity... – JBernardo – 2011-07-10T02:03:09.300

3@JBernado and even bigger since pow for bigint is more complicated story. – shabunc – 2011-08-19T08:49:41.017

2

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)

PhiNotPi

Posted 2011-01-28T01:49:09.830

Reputation: 26 739

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 – Ton Hospel – 2016-03-06T13:35:15.460

2

JAGL V1.0 - 13 / 11

1d{cdc+dcPd}u

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

11 bytes

1d{cdc+cd}u

globby

Posted 2011-01-28T01:49:09.830

Reputation: 1 132

2

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

pawel.boczarski

Posted 2011-01-28T01:49:09.830

Reputation: 1 243

2I don't think you need the [1 0]. Picking the second item out of the matrix will give you the right number anyway. – Andrew – 2015-04-16T21:37:47.863

2Thank 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). – pawel.boczarski – 2015-04-16T22:22:58.373

2

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

Mama Fun Roll

Posted 2011-01-28T01:49:09.830

Reputation: 7 234

2

Perl - 39 chars

($a,$b)=($b,$a+$b||1),print"$b
"while$=

Jay Chan

Posted 2011-01-28T01:49:09.830

Reputation: 21

2

Ruby, 28 bytes

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

Usage:

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

Vasu Adari

Posted 2011-01-28T01:49:09.830

Reputation: 941

2

, 3 chars / 6 bytes (noncompetitive)

Мȫï

Try it here (Firefox only).

More builtins!

math.js + numbers.js = hella functions

Mama Fun Roll

Posted 2011-01-28T01:49:09.830

Reputation: 7 234

2

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.

Charles

Posted 2011-01-28T01:49:09.830

Reputation: 2 435

2

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!

Conor O'Brien

Posted 2011-01-28T01:49:09.830

Reputation: 36 228

2

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.

Rɪᴋᴇʀ

Posted 2011-01-28T01:49:09.830

Reputation: 7 410

2

Python 2, 43 bytes

def f(n):k=9**n;return k**-~-~n/~-(k*~-k)%k

orlp

Posted 2011-01-28T01:49:09.830

Reputation: 37 067

2

Python, 36

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

Alexandru

Posted 2011-01-28T01:49:09.830

Reputation: 5 485

2

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

user5957401

Posted 2011-01-28T01:49:09.830

Reputation: 699

2

Python

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

Alexandru

Posted 2011-01-28T01:49:09.830

Reputation: 5 485

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. – Bakuriu – 2012-09-01T09:42:32.390

1a=b=1<newline>while 1:print a;a,b=b,a+b 30 Characters – st0le – 2011-02-01T06:19:34.337

@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 :) – Mikle – 2011-11-24T18:02:22.980

1

Javascript - 48 chars

for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}

Clean and simple... probably not a shortness winner :D

Here is the full implementation:

function a(n) {
    var i;
    var f = new Array();
    f[0]=1;

    for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}

    console.log(f);
}

Rastko

Posted 2011-01-28T01:49:09.830

Reputation: 111

1

tinylisp, 40 bytes

The language is much newer than question, of course.

(d f(q((x y)(i(disp x)1(f y(a x y
(f 0 1

This is a full program that outputs Fibonacci numbers until you stop it. Try it online!

The first line defines a function f that takes numbers x and y, outputs x, and calls f recursively on y and the addition of x and y. The main trick is the use of if to simulate a "do A, then B" structure: the disp call is used as the condition; its return is always falsey; so we put the recursion in the false branch.

The second line calls f with 0 and 1.

DLosc

Posted 2011-01-28T01:49:09.830

Reputation: 21 213

1

J-uby, 8 6 bytes

:++2.*

In J-uby, + on a proc (or a symbol in this case, as symbols can be used as procs in J-uby), defines a recurrence relation. It takes a starter array, and then produces a function that takes n, and then applies itself to the starter array n times, pushing the result to the end and removing the first element. Naturally :+ + [0,1] is a recurrence relation that starts with elements 0, 1 and adds them together n times.

2.* is shorthand for [0,1]

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

1

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

SL2

Posted 2011-01-28T01:49:09.830

Reputation: 171

Surely, with APL's prodigious operator vocabulary, it should be able to compete in size with the GolfScript one? ;-) – Chris Jester-Young – 2013-04-08T11:32:46.603

@ChrisJester-Young Oh probably, but I only started learning APL today... – SL2 – 2013-04-08T23:41:24.677

1

C#: 83 69 68 66 58 53 51

I used a nasty trinary and recursive lambda expression to achieve this one.

Source: StackOverflow

Func<ulong,ulong> f=null;f=x=>x<2?x:f(x-2)+f(x-1);

Usage:

    public static void Main()
    {
        // Recursive lambda expression...
        Func<ulong, ulong> f = null;
        f = x => (x < 2) ? x : f(x - 2) + f(x - 1);

        Console.WriteLine("Please enter a whole number to obtain the Fibonacci sequence number for:");
        string value = Console.ReadLine();

        long numValue;
        if(UInt64.TryParse(value, out numValue))
            Console.WriteLine(f(numValue));

        Console.WriteLine("Press any key to end the program.");
        Console.ReadKey();
    }

Andrew Gray

Posted 2011-01-28T01:49:09.830

Reputation: 600

1I don't think you need the parentheses around (n<2) – Cyoce – 2016-05-02T15:00:38.203

Good catch! Updated. – Andrew Gray – 2016-05-02T15:06:28.180

2You don't have no support negative indices. Also, the "ternary" conditional operator isn't nasty if you use it right. :-) – Chris Jester-Young – 2013-04-08T15:21:25.953

That helps, thanks! I don't consider ternaries nasty usually, but in a case like the one I've posted, I would do everything in my power to avoid that getting into a codebase. It gets points for clever/short, but not readable. – Andrew Gray – 2013-04-08T15:28:33.887

1lol - I posted mine without ever seeing yours. Funny to see that they're almost identical. :) – Troy Alford – 2013-04-17T17:54:07.020

1Yeah, but trying to calculate anything above f(45) will cause either a StackOverflow, or just take forever and some time to calculate. – Andrew Gray – 2013-04-17T18:09:33.737

1

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.

Digital Trauma

Posted 2011-01-28T01:49:09.830

Reputation: 64 644

1

Alice, 11 bytes

This was a collaborative golfing effort with Sp3000.

1 \ O
,+{.3

Try it online!

This prints the Fibonacci sequence indefinitely, starting from 1,1, one integer on a line. Unfortunately, it's horrible in terms of memory, because it leaks one stringified copy of each number in the sequence. The things you do for bytes...

Explanation

1   Push 1 to initialise the sequence. There's already an implicit zero underneath.
\   Reflect to NE. Switch to Ordinal.
    Immediately reflect off top boundary, move SE.

    The remainder of the program runs in an infinite loop. At this point of the loop
    there's the current number F_n of the sequence on top of the stack, and the 
    previous number F_n-1 is below.

                                                            Stack:
                                                            [... F_n-1 F_n] 
.   Implicitly convert F_n to a string and duplicate it.    [... F_n-1 "F_n" "F_n"]
    Reflect off bottom boundary, move NE.
O   Output F_n with a trailing linefeed.                    [... F_n-1 "F_n"]
    Reflect off top right corner, move back SW.
.   Make another copy of F_n. (We don't need this one.)     [... F_n-1 "F_n" "F_n"]
    Reflect off bottom boundary, move NW.
\   Reflect to S. Switch to Cardinal.
{   Turn 90 degrees left, i.e. east.
.   Implicitly convert F_n to an integer and duplicate it.  [... F_n-1 "F_n" F_n F_n]
3   Push 3.                                                 [... F_n-1 "F_n" F_n F_n 3]
,   Pull up the third stack element, which is F_n-1.        [... "F_n" F_n F_n F_n-1]
+   Add F_n and F_n-1.                                      [... "F_n" F_n F_n+1]  
{   Turn 90 degrees left, i.e. north.
\   Reflect to SE. Switch to Ordinal.

    After this point, the loop repeats.

Martin Ender

Posted 2011-01-28T01:49:09.830

Reputation: 184 808

1

Taxi, 864 bytes

1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:W 1 R.[a]Go to Cyclone:N 1 L.Pickup a passenger going to The Babelfishery.Pickup a passenger going to Addition Alley.Go to Fueler Up:N 2 R, 2 R.Go to The Babelfishery:S.Pickup a passenger going to Post Office.Go to Post Office:N 1 L 1 R.Go to Sunny Skies Park:S 1 R 1 L 1 R.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Addition Alley:N 2 R 1 R.Pickup a passenger going to Sunny Skies Park."," is waiting at Writer's Depot.Go to Writer's Depot:N 1 L 1 L.Pickup a passenger going to Post Office.Go to Sunny Skies Park:N 2 R.Switch to plan "a".

Try it online!

Ungolfed:

1 is waiting at Starchild Numerology.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd right 1st left 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to Cyclone.
Go to Sunny Skies Park: west 1st right.
[a]
Go to Cyclone: north 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to Addition Alley.
Go to Fueler Up: north 2nd R, 2nd right.
Go to The Babelfishery: south.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
Go to Sunny Skies Park: south 1st right 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Cyclone.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to Sunny Skies Park.
"," is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st left.
Pickup a passenger going to Post Office.
Go to Sunny Skies Park: north 2nd right.
Switch to plan "a".

Engineer Toast

Posted 2011-01-28T01:49:09.830

Reputation: 5 769

1

Braingolf, 23 bytes

1!_# @.!_[# @!+!_<1+>];

Try it online!

totallyhuman

Posted 2011-01-28T01:49:09.830

Reputation: 15 378

17 bytes – Skidsdev – 2017-06-16T09:20:12.353

14 bytes – Skidsdev – 2017-06-16T09:23:40.353

8 bytes for output the nth number – Skidsdev – 2017-06-16T09:35:59.437

1

Joy, 45 bytes

DEFINE f ==[2<][][[1 - f][2 - f]cleave+]ifte.

Try it online! Zero-indexed. Example usage: 6 f yields 8.

[2<]                         ifte . if the top stack element is less than two  
    []                            . then do nothing
      [              cleave ]     . else duplicate the element and apply two functions
                           +      . and sum the results
       [1 - f][2 - f]             . where the functions compute the two previous Fibonacci numbers

Alternative (same byte count):

DEFINE f ==[2<][][dup 1 - f swap 2 - f+]ifte.

Laikoni

Posted 2011-01-28T01:49:09.830

Reputation: 23 676

1

cQuents, 6 bytes

=1:z+y

Try it online!

This works both with and without input - it prints the sequence without input, and the nth item (1-indexed) with input n.

For 0, 1, 1, ... version, 8 bytes:

=0,1:z+y

Try it online!

Explanation

=1      Set first item in sequence to 1
  :     Mode: Sequence 1 (prints sequence with no input, or nth item with input n
   z+y  Each term equals the previous two terms added together (defaults to 0)

I really, really like the way this language is going :)

Stephen

Posted 2011-01-28T01:49:09.830

Reputation: 12 293

Note current version uses Z and Y instead of z and y – Stephen – 2019-02-01T04:54:59.250

1

ReRegex, 50 bytes.

(0+),(0+):0/$1,$2,$1$2:/.*?(0+),0+:$/$1/0,0:#input

0 indexed. Takes input and gives output via Unary.

Try it online!

About the Program

ReRegex was designed to be much like an advanced version of ///. It offers the same very basic concept of repeatedly doing string match and replace operations. However, that's where the similarities end. ReRegex instead uses a list of match and replace operations, separated by /s, to perform in a loop, and the original string to effect. The Regexes will continue being performed on the original string until a constant state is achieved, at which point the program will dump the string to STDOUT.

This program in particular is just 2 regular expressions and then the input with some default values.

(0+),(0+):0  -> $1,$2,$1$2:
.*?(0+),0+:$ -> $1

And the input is formatted with;

0,0:#input

ReRegex defaultly replaces #input with whatever is passed to the program on STDIN.

For an example, let's say 00000 is passed to STDIN. First, the "Memory" looks like this:

0,0:00000

In the first loop, the regex (0+),(0+):0 is matched, the replace then creates the next itteration of the fibonnachi sequence.

0,0,00:0000

And in doing so, it also pops one of the 0's off, which is why :0 is at the tail end of the match, but not the replace. This then happens 4 more times in a row.

0,0,00,000,00000,00000000,0000000000000:

Now that first regex doesn't match, as there's no more :0 at the end, so we're almost at a stable end point. Now that there's nothing after :, .*?(0+),0+:$ matches, and all it does is clear all data but the second last group of 0s.

00000000

Now, nothing else matches, so it's outputted.

ATaco

Posted 2011-01-28T01:49:09.830

Reputation: 7 898

1

Joy, 28 bytes

[2<][][1 - dup 1 -][+]binrec

Try it online!

alephalpha

Posted 2011-01-28T01:49:09.830

Reputation: 23 988

1

Husk, 7 2 bytes (non-competing)

İf

Try it online!

ბიმო

Posted 2011-01-28T01:49:09.830

Reputation: 15 345

1

Forth, 39 36 bytes

0 1 : f BEGIN 2DUP + ROT . AGAIN ; f

Explanation

First 0 and 1 are pushed to the stack. Then starts an endless loop where 2DUP duplicates the top two stack items which are then summed with +. At this point stack is 0 1 1. Then the bottom item of the stack is moved on top with ROT. . prints and removes the item on the top of the stack. Creates an endless sequence of Fibonacci numbers.

Had to check out what's Forth about. And is there a better way to learn than trying to golf Fibonacci series. I see that there's already an answer with Forth but desided to post anyway. At least this is a different approach.

SydB

Posted 2011-01-28T01:49:09.830

Reputation: 31

1

Proton, 24 bytes

f=a=>a<2?1:f(a-1)+f(a-2)

Try it online!

(Not working on TIO yet; waiting for pull)

The @ is not necessary but it enables caching for the lambda which makes it considerably faster (as in, it actually finishes in a reasonable amount of time). That being said, when I tried computing it up to 10000 (which I needed to increase sys.setrecursionlimit to do), it gave me a Segmentation Fault because the program ran out of memory (Proton is very inefficient) :P

HyperNeutrino

Posted 2011-01-28T01:49:09.830

Reputation: 26 575

Polyglot with ES6. – Zacharý – 2017-08-12T21:54:33.933

@Zacharý Huh that's cool. This is weird; Proton is often a polyglot with Python too :P – HyperNeutrino – 2017-08-13T00:51:42.340

1

Recursiva, 16 bytes

<a3:1!+#~a$#~~a$

Try it online!

Explanation:

<a3:1!+#~a$#~~a$
<a3:1            - If a<3 then 1
     !           - Else
      +          - Sum
       #~a$      - Call Self but with parameter a-1, will be replaced by result
           #~~a$ - Call self but with parameter a-2, will be replaced by result      

officialaimm

Posted 2011-01-28T01:49:09.830

Reputation: 2 739

1

Chip-8, 36 bytes

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

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

This one writes the numbers into memory:

6001
A300
8014
F055
8013
8103
8013
1204

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

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

12Me21

Posted 2011-01-28T01:49:09.830

Reputation: 6 110

1

VBA, 28 Bytes

Anonymous VBE immediate window function that takes no input and infinitely outputs the n-th term of the Fibonacci Sequence while iterating n

i=1:Do:k=i+j:i=j:j=k:?j:Loop

Taylor Scott

Posted 2011-01-28T01:49:09.830

Reputation: 6 709

1

Brain-Flak, 36 34 32 bytes

({}(())){({}[()]<(({})<>{})>)}<>

Outputs the nth number of the zero indexed Fibonacci sequence (F(0) = 1, F(1) = 1, etc.)

Try it online!

Explanation coming soon...

0 '

Posted 2011-01-28T01:49:09.830

Reputation: 3 439

1

><>, 12 Bytes

10:r+:nao20.

Output:

1
1
2
3
5
...

Could save 2 bytes by removing the new line, but then there would be no separation in the output at all.

Explanation:

Pretty basic. Start by pushing 1, 0 to the stack. Duplicate the top item, reverse the stack, and sum the top two items. If we had f_n, f_n-1 on the stack before, we now have f_n+1, f_n. Duplicate the top item, and print it. 'ao' prints a new line. '20.' moves the pointer to (2,0) in the codebox, which is right after the '10'. Start again.

Bolce Bussiere

Posted 2011-01-28T01:49:09.830

Reputation: 970

1

Pyt, 1 byte

Get the nth Fibonacci number:

Explanation:

           Implicit input
 Ḟ         Return (input)-th Fibonacci number

Try it online!

Pyt, 7 bytes

Get an infinite list of Fibonacci numbers:

0`ĐḞƤ⁺ł

Explanation:

0           Push 0 [this is the counter]
 `    ł     While the counter is not zero (checked at 'ł')
  Đ         Duplicate the counter
   ḞƤ       Print the (counter)-th Fibonacci number
     ⁺      Increment the counter

Try it online!

mudkip201

Posted 2011-01-28T01:49:09.830

Reputation: 833

1

QBasic, 32 bytes

b=1
DO
?b
b=b+a
a=b-a
SLEEP
LOOP

Generates and prints Fibonacci numbers forever. SLEEP waits for a user keypress between numbers; otherwise, the output would scroll off the screen very rapidly.

DLosc

Posted 2011-01-28T01:49:09.830

Reputation: 21 213

1

Add++, 74 bytes

D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,r,@,¿1=,1,bM¿
D,g,@,¿1_,1_001${f},1¿{r}

Try it online!


Old version, 75 bytes

D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,r,@:,1b]$oVcGbM
x:?
-1
I,$f>x>0>1>0
$r>x

Try it online!

It's long, but I rather this than have a builtin. Takes a single input n, and outputs the nthe Fibonacci number.

How it works

Executable demonstration with an example input of 8:

D,fib,@@@@*,	; Create a tetradic function 'fib'
		; This returns the nth and (n-1)th fib number
		; Example arguments:	[8 0 1 0]
	V	; Save the top value;	[8 0 1]	  ; 0
	$	; Swap;			[8 1 0]	  ; 0
	2D	; Take the 2nd value;	[8 1 0 1] ; 0
	+	; Sum;			[8 1 1]	  ; 0
	G	; Retrieve;		[8 1 1 0]
	1+	; Increment;		[8 1 1 1]
	d	; Duplicate;		[8 1 1 1 1]
	A	; Push the arguments;	[8 1 1 1 1 8 0 1 0]
	ppp	; Pop 3 values;		[8 1 1 1 1 8]
	=	;   Cond: Equal?	[8 1 1 1 0]
	0$Qp	;   If: Return 0
	{fib}p	;   Else: Call 'fib' again
                ; Eventually, this returns:
		;	[7 13 21 7 0]

D,ret,@:,	; Create a monadic function 'ret' that outputs the final result
		; Example argument:	[[7 13 21 7 0]]
	1b]	; Push [1];		[[7 13 21 7 0] [1]]
	$	; Swap;			[[1] [7 13 21 7 0]]
	o	; Logical OR;		[[1] [7 13 21 7 0]]
	VcG	; Clear all but one;	[[7 13 21 7 0]]
	bM	; Take the maximum;	[21]

x:?		; Take input;		x = 8
-1		; Decrement;		x = 7
I,		; If x != 0:
	$fib>x	;	Call 'fib'	x = [7 13 21 7 0]
	>0>1>0	; 
$ret>x		; Call 'ret'		x = 21

Try it online!

caird coinheringaahing

Posted 2011-01-28T01:49:09.830

Reputation: 13 702

1

FALSE, 13 bytes

1 1[1][$2ø+]#

Numbers are pushed to the stack.

12Me21

Posted 2011-01-28T01:49:09.830

Reputation: 6 110

1

Japt, 3 bytes

Just to add to the collection.

0-indexed, using 0 as the first number in the sequence.

MgU

Try it

Shaggy

Posted 2011-01-28T01:49:09.830

Reputation: 24 623

1

><>, 11 bytes

10r:n:@+aor

Try it online!

Prints the Fibonacci sequence forever, separated by newlines.

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

1

C, 45 (37)

Only because it's easy:

f(n){return n<2?n?1:0:f(n-1)+f(n-2);}

Or the more compiler-friendly/standards-compliant but more verbose version:

#define m main(n
m){return n<2?n?1:0:m-1)+m-2);}

note: once compiled, you have to call main() with an actual value (which will likely take some command line fiddling depending on OS)

Stuntddude

Posted 2011-01-28T01:49:09.830

Reputation: 586

n?1:0 can be replaced with just n. – Cyoce – 2016-05-02T15:23:21.127

Doesn't run for me. – Johannes Kuhn – 2013-11-28T22:53:01.040

It only runs as a stand-alone in some environments with very specific settings. I'll add a friendlier version though. – Stuntddude – 2013-11-28T23:48:23.667

Number of arguments could work. Intresting way to pass the parameter. – Johannes Kuhn – 2013-11-29T07:15:40.863

1

Befunge, 15 13 characters

1:.:00p+00g\#

I didn't spot any Befunge solutions, so I thought I'd write one. Too bad Befunge doesn't have a rotate-n operation, and trampoline # doesn't work at end-of-line to skip first character after looping around. Turns out that part of the spec is considered ambiguous on that point, and my initial interpretation is actually valid.

FireFly

Posted 2011-01-28T01:49:09.830

Reputation: 7 107

1

Coconut, 28 bytes

def f(a=1,b=1)=[a]::f(b,a+b)

Try it online!

ovs

Posted 2011-01-28T01:49:09.830

Reputation: 21 408

1

Forked, 17 15 bytes

01v
  >sP+%A!"U

Try it online!

This uses the same method as my Implicit answer.

The first line sets up the stack: pushes 0, pushes 1, and then directs the control flow South.

The > on the second line turns the IP East where it hits the main code:

sP+%A!"U
  • s - swap top two stack values
  • P - pop top of stack, store in register
  • + - pop top two stack values, add together, push result
  • % - print top of stack as integer
  • A! - print 0xA as codepoint character (ASCII newline)
  • " - swap top two stack values
  • U - push register to stack

Since the IP wraps, this line is executed infinitely.

MD XF

Posted 2011-01-28T01:49:09.830

Reputation: 11 605

1

R16K1S60 Assembly, 36 bytes

mov bx, ip
mov ax, ip
mov sp, data
jmp inner
prg:
mov cx, [sp+ax]
mov [sp+bx], cx
inner:
mov ex, [sp]
mov dx, [sp+bx]
mov [sp], dx
add ex, dx
mov [sp+ax], ex
send ax, ex
jmp prg

data:
dw 0x0000
dw 0x0001

Pretty simple. Abuses 7 registers, including the instruction pointer (for some predefines)

To note why I used the IP instead of a constant, it's because the R16K1S60 has to use an extra word (two bytes) to encode a constant into an instruction.

Alongside that, I used ax and bx instead of ex and dx for the offset because ex and dx cannot be referenced in only 3 bits (the size of the offset section of instructions that support it)

Outputs the number as a word on port 2

moonheart08

Posted 2011-01-28T01:49:09.830

Reputation: 693

1

Retina 0.8.2, 23 bytes

.+
$*
+`11(1*)
1$1 $1
1

Try it online! Explanation:

.+
$*

Convert to unary.

+`11(1*)
1$1 $1

Repeatedly replace all n greater than 1 with copies of n-1 and n-2, thus calculating f(n) = f(n-1) + f(n-2) for n greater than 1.

1

Count the remaining 1s, as f(0) = 0 and f(1) = 1.

Neil

Posted 2011-01-28T01:49:09.830

Reputation: 95 035

1

x86 assembly (32-bit), 14 bytes

Bytecode:

58 59 50 41 31 c0 99 40 01 c2 92 e2 fb c3

That 3-byte add/xchg is quite concise :-)

1-indexed.

0:   58                      pop    %eax
1:   59                      pop    %ecx
2:   50                      push   %eax
3:   41                      inc    %ecx
4:   31 c0                   xor    %eax,%eax
6:   99                      cltd   
7:   40                      inc    %eax
8:   01 c2                   add    %eax,%edx
a:   92                      xchg   %eax,%edx
b:   e2 fb                   loop   8
d:   c3                      ret

ObsequiousNewt

Posted 2011-01-28T01:49:09.830

Reputation: 836

1

Ahead, 15 bytes

1loN+{<
>\:O\:^

Uses signed 32-bit ints so eventually reaches overflow and wraps negative. Starts at 0, which is technically correct?

Try it online!

snail_

Posted 2011-01-28T01:49:09.830

Reputation: 1 982

1

Tidy, 15 bytes

recur2(1,1,(+))

Try it online! Returns an infintie range of Fibonacci numbers.

Explanation

recur2 defines a recursive function which takes the previous 2 items and applies a function to them, in the case, addition. This is equivalent to saying "the first two entries are both 1 and every entry after that is the sum of the previous two".

Conor O'Brien

Posted 2011-01-28T01:49:09.830

Reputation: 36 228

1

Alumin, 19 bytes

zhdnqhhhhhdaodradnp

Try it online!

Explanation

zhdnqhhhhhdaodradnp
zh                    push 0, 1                 [0, 1]
  dn                  output 1                  [0, 1]
    q             p   loop (forever)            
     hhhhh            push 5                    [0, 1, 5]
          da          double (10)               [0, 1, 10]
            o         output as char (newline)  [0, 1]
             d        duplicate TOS             [0, 1, 1]
              r       reverse stack             [1, 1, 0]
               a      add top two               [1, 1]
                dn    output top w/out popping  [1, 1]

Conor O'Brien

Posted 2011-01-28T01:49:09.830

Reputation: 36 228

1

Pascal (FPC), 70 bytes

var i,j:word;begin i:=1;repeat writeln(i);i:=i+j;j:=i-j until 1<0 end.

Try it online! (limited)

Prints the sequence forever, 1-indexed.

Explanation:

var i,j:word;   //declare 2 integers, i and j;
                //word gives range [0,65535];
                //for bigger ranges, you can use Int32, Int64 or QWord
begin
  i:=1;         //set i to 1
                //j has not been set, so it gets 0 as initial value
  repeat        //start a block to be repeated (first time enters unconditionally)
    writeln(i); //write current value of i with a newline to separate numbers
                //i needs to get the value of the next number, which is obtained by adding i and j
    i:=i+j;     //j is used to keep track of the last written value
    j:=i-j      //which is used in the next iteration;
                //since i is now the sum of 2 previous values in the sequence
                //and j is the earlier one, the later one can be obtained
                //by substracting current j from i
  until 1<0     //end a block to be repeated
                //condition is always false, so the program will loop in repeat block forever
end.

AlexRacer

Posted 2011-01-28T01:49:09.830

Reputation: 979

1

Rust, 100 characters

|n|{let mut a=1u64;let mut b=1u64;let mut s=vec![a,b];for _ in 0..n {let t=b;b=a+b;a=t;s.push(b);}s}

A closure that takes an integer n as input and returns a vector of the first n items of the Fibonacci sequence.

T_human

Posted 2011-01-28T01:49:09.830

Reputation: 31

You could shave off a few bytes given the fact that you don't have to return all the Fibonacci numbers, just the nth one. – Loovjo – 2018-09-23T15:06:53.493

1

Python 3, 43 Bytes

a,c=0,0;b=1
while 1:print(a);c=a+b;a=b;b=c

CodeGolfer

Posted 2011-01-28T01:49:09.830

Reputation: 31

1Note that Python has a swap statement to avoid having to use an extra variable: a,b=b,a+b. Also, there are plenty of shorter Python answers already posted. – FlipTack – 2018-12-17T20:21:49.180

Also, 0 isn't supposed to be included in this challenge. – Ørjan Johansen – 2018-12-18T01:30:33.237

1

Pure, 66 bytes

using system;do(printf"%Zd\n")(f 1L 1L with f a b=a:f b(a+b)&end);

Try it online!

First answer in Pure \o/

Prints until TIO stops it or the heat death of the universe, whatever comes first.

How:

using system;do(printf"%Zd\n")(f 1L 1L with f a b=a:f b(a+b)&end); // Anonymous lambda;
using system;                                                      // Import system functions
             do                                                    // Infinite loop
               (printf"%Zd\n")                                     // Print bigints + linefeed
                              (f 1L 1L                             // Declare f with 2 bigint args
                                                                   // starting with 1
                                       with f a b=                 // with f(a,b) being
                                                  a:f b(a+b)       // a list from a until f(b,(a+b));
                                                            &      // transformed into a stream
                                                                   // to prevent overflowing
                                                             end);

J. Sallé

Posted 2011-01-28T01:49:09.830

Reputation: 3 233

1

IBM PC 8087 FPU, 119 113 bytes

This will compute up to Fibonacci n=87 (679891637638612258) using only the Intel 8087 math-coprocessor. Might not be the smallest code, but it will run on an original IBM PC from 1981 (with optional 8087 chip of course).

Very impressive that the PC was capable of 80-bit extended-precision floating point arithmetic in hardware back then!

Try it on DOS!

    MOV  AX, DS:[82H]   ; get two digits from command line
    CMP  BYTE PTR DS:[80H], 2 ; check if only one digit + space?
    JG   A2I            ; if <= 2, use the first two
    JL   DEF_VAL        ; if no input, use default MAX (87)
    XCHG AL, AH         ; else only one digit
    MOV  AL, '0'        ; pad byte with 0
    JMP  A2I
DEF_VAL:
    MOV  AX, '78'       ; default value (endian reversed)
A2I:
    SUB  AX, '00'       ; convert from ASCII
    JZ   DEF_VAL        ; if input is 0, use default value
    XCHG AL, AH         ; endian convert
    AAD                 ; base convert from 10 to binary
    MOV  CX, AX         ; set up loop counter
    FLD1                ; ST(1) = 1
    FLDZ                ; ST  = 0
FIB_LOOP:
    FADD ST(1), ST      ; ST(1) = ST(1) + ST
    FSUBR ST, ST(1)     ; ST = ST(1) - ST
    CALL PRINT_ST       ; print the BCD number
    LOOP FIB_LOOP
EXIT:
    MOV  AH, 4CH        ; exit to DOS
    INT  21H

PRINT_ST PROC
    PUSH CX             ; save CX
    MOV  SI, SP         ; use SI for index of BCD data
    SUB  SP, 10         ; reserve 10 bytes from stack
    FLD  ST             ; push (copy) ST since FBSTP pops stack 
    FBSTP [SI][-10]     ; pop ST into BCD
    SUB  SI, 2          ; skip first byte (sign), and move to next
    MOV  CH, 9          ; 9 bytes
    MOV  CL, 4          ; shift 4 times
    MOV  AH, 2          ; DOS display char function
PB_LOOP:
    MOV  DL, [SI]       ; get byte
    SHR  DL, CL         ; high digit to low nibble
    OR   DL, '0'        ; convert to ASCII
    INT  21H            ; display digit
    MOV  DL, [SI]       ; get byte again
    AND  DL, 0FH        ; mask out high nibble
    OR   DL, '0'        ; convert low digit to ASCII
    INT  21H            ; display digit
    DEC  SI             ; next byte
    DEC  CH             ; more digits?
    JG   PB_LOOP        ; yes, repeat
PB_CRLF:
    MOV  DL, 0DH        ; display newline CRLF
    INT  21H
    MOV  DL, 0AH
    INT  21H
    ADD  SP, 10         ; put stack back the way it was
    POP  CX
    RET
PRINT_ST ENDP

I/O

Takes n-th term as input on the command line, and displays up to that (zero padded to 18 digits). If no number is specified will display up to the max (n=87) that can be handled by the FPU.

A>FIB 10
000000000000000001
000000000000000001
000000000000000002
000000000000000003
000000000000000005
000000000000000008
000000000000000013
000000000000000021
000000000000000034
000000000000000055

A>FIB
000000000000000001
000000000000000001
000000000000000002
000000000000000003
000000000000000005
000000000000000008
000000000000000013
000000000000000021
000000000000000034
000000000000000055
000000000000000089
000000000000000144
000000000000000233
000000000000000377
000000000000000610
000000000000000987
000000000000001597
000000000000002584
000000000000004181
000000000000006765
000000000000010946
000000000000017711
000000000000028657
000000000000046368
000000000000075025
000000000000121393
000000000000196418
000000000000317811
000000000000514229
000000000000832040
000000000001346269
000000000002178309
000000000003524578
000000000005702887
000000000009227465
000000000014930352
000000000024157817
000000000039088169
000000000063245986
000000000102334155
000000000165580141
000000000267914296
000000000433494437
000000000701408733
000000001134903170
000000001836311903
000000002971215073
000000004807526976
000000007778742049
000000012586269025
000000020365011074
000000032951280099
000000053316291173
000000086267571272
000000139583862445
000000225851433717
000000365435296162
000000591286729879
000000956722026041
000001548008755920
000002504730781961
000004052739537881
000006557470319842
000010610209857723
000017167680177565
000027777890035288
000044945570212853
000072723460248141
000117669030460994
000190392490709135
000308061521170129
000498454011879264
000806515533049393
001304969544928657
002111485077978050
003416454622906707
005527939700884757
008944394323791464
014472334024676221
023416728348467685
037889062373143906
061305790721611591
099194853094755497
160500643816367088
259695496911122585
420196140727489673
679891637638612258

Size Notes

As is typical with machine code and simple programs, I/O and data type conversion takes up the large majority of the code. For example, of the 113 byte FIB.COM executable:

  • 59 bytes to display an 8087 register as a decimal number to the screen
  • 31 bytes to handle and sanitize two digits of command line input
  • 18 bytes to calculate Fibonacci number sequence
  • 4 bytes to gracefully exit to DOS (yes, I could maybe get away with a 1 byte RET)
  • 1 byte for a NOP instruction added automatcially by MASM for alignment purposes

640KB

Posted 2011-01-28T01:49:09.830

Reputation: 7 149

1

Python 3, 37 bytes

lambda p,a=5**.5:round((.5+a/2)**p/a)

Try it online!

Explanation

Fib(n) = Fib(n-1) + Fib(n-2) with Fib(0) = Fib(1) = 1

Using some simplification, this becomes:

Fibonacci Golden Ratio

For n > 0, this becomes

n greater than 0

Where round is a function that rounds to the nearest integer.

lambda p,                              # defines the anonymous function
         a=5**.5:                      # sets a to \sqrt{5}
                 round((.5+a/2)**p/a)  # Runs the function and returns the result

Martmists

Posted 2011-01-28T01:49:09.830

Reputation: 429

This loses precision at only n=71, outputting 308061521170130 instead of 308061521170129 – Jo King – 2019-07-26T04:58:46.330

1

Awk, 35 bytes

BEGIN{for(y=1;z=x+y;y=z)print(x=y)}

Try it online

James Brown

Posted 2011-01-28T01:49:09.830

Reputation: 663

1

BitCycle, 21 bytes

  1+ ~!
CB0CA~
^ 1  <

Outputs an unending sequence. Use the -u flag to get output in decimal. Try it online!

Note: the current BitCycle interpreter doesn't play very well with infinite output. You have to halt the program (Ctrl-C) before it displays anything. On TIO, letting the program run until the 60-second timeout shows no output, either--you have to click the Run button (or hit Ctrl-Enter) again to halt it.

Explanation

This explanation assumes you're familiar with BitCycle.

Conceptually, we store two numbers at a time, the smaller and the larger. At each step, we output the larger, set the new larger to be the larger plus the smaller, and set the new smaller to be the larger.

We store and output the numbers in unary (using 1 bits), but we also need a separator (0 bit) after each number output. Our approach is to store the separator at the end of each number. When adding two numbers, we discard the separator from the first number added, and keep the separator from the second number added.

In the code, the leftmost C collector holds the smaller number, while the rightmost C collector holds the larger. We're actually going to store everything negated, so the numbers are made of 0 bits and the separators are 1 bits. Thus, the leftmost C initially gets a single 1 (unary zero plus a separator bit) and the rightmost C gets 01 (unary one plus a separator bit).

The C collectors open and dump their contents straight into the B and A collectors.

Next, the A collector opens, holding the larger number. It goes through a couple of dupneg devices, with the following results:

  • A copy goes into the leftmost C collector, becoming the new smaller number.
  • A negated copy goes into the sink ! and is output.
  • A doubly-negated copy goes into the rightmost C collector, but the + ensures that it's only the 0 bits, not the trailing 1 separator.

Finally, the B collector opens and dumps its contents into the rightmost C, adding the former smaller number to the former larger number to create the new larger number. The cycle repeats forever.

Other versions

Here's a modified version (still 21 bytes) that strips the separator off the smaller number (instead of the larger) before adding:

10>v ~!
BA+BA~
^    <

And here's an 18-byte version that starts at 0 instead of 1. (Thanks to Jo King for golfing it down from 21 bytes.) Here, we start with the "smaller" number at 1 and the "larger" number at 0, generating the extended Fibonacci sequence 1,0,1,1,2,3,... (Since the "larger" number is what we output, we don't see the first 1.)

 1+ ~!
CBCA~
^10 <

DLosc

Posted 2011-01-28T01:49:09.830

Reputation: 21 213

1

BitCycle, 17 16 bytes

~1~ +
AB~/!
^ +/

Try it online!

Outputs the 0 based sequence. This could be 14 bytes:

~1~+
AB~!
^ +/

Try it online!

But it prints an extra 0 in front of the sequence, which takes a couple of bytes to fix...

There's also a 17 byte solution:

v0<
AB~
~ +\
~  !

Try it online!

Which I like because you can switch between 0-based and 1-based just by changing the 0 on the first line to a 1.

For both solutions, the numbers are infinitely output is in unary 1 bits separated by 0 bits. The -u flag converts the unary numbers to decimal instead, but the TIO tends to cut off the outputting section sometimes, and the last number is always truncated too. There's a bit in the footer to prevent this.

Explanation:

Basically, these solutions only use a single pair of collectors and distinguishes between the two numbers by storing one as unary 1 bits and the other as unary 0 bits.

This starts off with 1 being pushed to the collectors to initialise the sequence.

~ ~    Invert the whole stack
AB~    This basically swaps the values of the two numbers
       Also duplicate a copy downwards and rightwards
       Split the stream into zeroes and ones with the plus
!  /!  Print a single 0 as the separator
^ +/   And add a copy of the 1s to the collector
  ~ +
    !  Print a copy of the 1s to the output

This repeats infinitely, basically executing the pseudocode:

a=0
b=1
while 1:
    oldA = a
    b,a = a,b
    print ','
    a += oldA
    print oldA

Jo King

Posted 2011-01-28T01:49:09.830

Reputation: 38 234

1

Keg, 10 bytes

01{:. ,:"+

Endlessly outputs numbers separated by spaces

How it works

0    Pushes 0
1    Pushes 1
{    Begins an endless while loop
:.   Outputs the top item of the stack
 ,   Outputs a space
:"   Duplicates the top item of the stack and puts it at the bottom
+    Adds the top two numbers of the stack

Try it Online!

EdgyNerd

Posted 2011-01-28T01:49:09.830

Reputation: 1 106

1

Brachylog, 10 bytes

0;1⟨t≡+⟩ⁱh

Try it online!

Generates an infinite list of Fibonacci numbers through the output variable.

Brachylog, 14 12 bytes

0;1⟨{tẉ₂}↰+⟩

Try it online!

Prints terms infinitely, separated by newlines.

0;1             Starting with [0,1],
    {tẉ₂}       get and print the second element,
          +     sum the two elements,
   ⟨     ↰ ⟩    and recur on the pair of those two values.

A variant to find the nth term of the sequence, 0-indexed:

Brachylog, 13 bytes

∧0;1⟨t≡+⟩ⁱ↖?t

Try it online!

Unrelated String

Posted 2011-01-28T01:49:09.830

Reputation: 5 300

An interesting (very slow) 12-byter, 0-indexed but wrong on element 0: {ḃ₁~clᵐ⌉<3}ᶜ

– Unrelated String – 2019-11-20T23:45:30.637

1

x86 Machine Code (ELF format) - 484 bytes

This program will calculate fibonacci digits until there is no memory left, so you might want to process the output to get Nth one you are looking for.

Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000  7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00  .ELF............
00000010  02 00 03 00 01 00 00 00 C0 80 04 08 34 00 00 00  ........Ŕ€..4...
00000020  00 00 00 00 00 00 00 00 34 00 20 00 02 00 28 00  ........4. ...(.
00000030  00 00 00 00 01 00 00 00 00 00 00 00 00 80 04 08  .............€..
00000040  00 00 00 00 E4 01 00 00 00 10 00 00 05 00 00 00  ....ä...........
00000050  00 10 00 00 01 00 00 00 00 00 00 00 00 90 04 08  ................
00000060  00 00 00 00 00 00 00 00 00 00 10 00 06 00 00 00  ................
00000070  00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000080  51 B9 00 90 04 08 88 01 31 C0 BA 01 00 00 00 EB  Qą......1Ŕş....ë
00000090  03 51 89 C1 31 C0 89 C3 43 B0 04 CD 80 31 C0 99  .Q‰Á1Ŕ‰ĂC°.Í€1Ŕ™
000000A0  42 59 C3 00 00 00 00 00 00 00 00 00 00 00 00 00  BYĂ.............
000000B0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
000000C0  31 C0 99 42 B9 03 90 04 08 C6 41 01 0A C6 41 02  1Ŕ™Bą....ĆA..ĆA.
000000D0  01 C6 41 03 01 3A 71 03 0F 84 FF 00 00 00 3A 71  .ĆA..:q..„˙...:q
000000E0  03 74 26 80 41 03 05 0F B6 41 03 6B C0 08 00 41  .t&€A...¶A.kŔ..A
000000F0  04 8A 41 04 E8 87 FF FF FF 80 69 04 30 C6 41 03  .ŠA.č‡˙˙˙€i.0ĆA.
00000100  01 83 E9 03 3A 71 03 75 DA 8A 41 04 E8 6F FF FF  ..é.:q.uÚŠA.čo˙˙
00000110  FF 3A 71 06 0F 84 BA 00 00 00 0F B6 41 05 88 41  ˙:q..„ş....¶A..A
00000120  06 0F B6 41 07 88 41 05 0F B6 41 07 00 41 06 C6  ..¶A..A..¶A..A.Ć
00000130  41 07 00 3A 71 06 0F 84 88 00 00 00 C6 41 07 01  A..:q..„....ĆA..
00000140  FE 49 06 3A 71 06 0F 84 78 00 00 00 C6 41 07 02  ţI.:q..„x...ĆA..
00000150  FE 49 06 3A 71 06 0F 84 68 00 00 00 C6 41 07 03  ţI.:q..„h...ĆA..
00000160  FE 49 06 3A 71 06 0F 84 58 00 00 00 C6 41 07 04  ţI.:q..„X...ĆA..
00000170  FE 49 06 3A 71 06 74 4C C6 41 07 05 FE 49 06 3A  ţI.:q.tLĆA..ţI.:
00000180  71 06 74 40 C6 41 07 06 FE 49 06 3A 71 06 74 34  q.t@ĆA..ţI.:q.t4
00000190  C6 41 07 07 FE 49 06 3A 71 06 74 28 C6 41 07 08  ĆA..ţI.:q.t(ĆA..
000001A0  FE 49 06 3A 71 06 74 1C C6 41 07 09 FE 49 06 3A  ţI.:q.t.ĆA..ţI.:
000001B0  71 06 74 10 FE 41 08 FE 41 09 FE 49 06 0F B6 41  q.t.ţA.ţA.ţI..¶A
000001C0  06 88 41 07 C6 41 06 01 83 C1 03 3A 71 06 0F 85  ..A.ĆA...Á.:q..…
000001D0  46 FF FF FF 3A 71 03 0F 85 01 FF FF FF B3 00 31  F˙˙˙:q..….˙˙˙ł.1
000001E0  C0 40 CD 80                                      Ŕ@Í€

Krzysztof Szewczyk

Posted 2011-01-28T01:49:09.830

Reputation: 3 819

1

Jasmin, 120 bytes

Defines a class F with a static method f that calculates the nth Fibonacci number. My implementation is essentially an iterative solution that stores partially computed Fibonacci numbers on the stack.

.class F
.super java/io/File
.method static f(I)I
ldc 0
ldc 1
dup_x1
iadd
iinc 0 -1
iload_0
ifgt $-9
ireturn
.end method

Some interesting golfing tricks used

  1. Extending java/io/File is shorter than extending java/lang/Object (The super line cannot be omitted). I've check and File is tied for the shortest fully qualified class name.
  2. Making this an instance method would let me remove static from the method header but, then I would have to explicitly implement an empty constructor to make the function callable (costing quite a few bytes).
  3. Juggling the Fibonacci values on the stack turned out to be shorter than storing them in local variables.
  4. On the other hand it's worth storing the index in a local variable. This makes stack management easier (i.e. shorter) without too much extra length since there is an instruction for adding or subtracting from locals variables.
  5. Although the JVM technically requires that you declare the maximum stack size before hand with .limit stack 5, this can be omitted if the class file is executed with the -noverify flag. I'm pretty sure this is some sort of undefined behavior but, it works in this this case.

Test setup

To test the code you, need a main method to invoke the static method.

class FibTest {
    public static void main(String[] args){
        for(int i = 0; i < 20; i++){
            System.out.println(F.f(i));
        }
    }
}

You then need to use jasmin.jar (obtained from the source forge linked in the title) to build F.class before building and executing the test file. Since the stack size was omitted, you need to execute the class with -noverify. The makefile below handles this.

test: FibTest.class
    java -noverify FibTest

FibTest.class: FibTest.java F.class
    javac FibTest.java    

F.class: F.j
    java -jar jasmin.jar F.j

ankh-morpork

Posted 2011-01-28T01:49:09.830

Reputation: 1 350

1

Gol><>, 7 bytes

12K+:N!

Byte knocked off courtesy of JoKing

Try it online!

9 bytes

01T2K+:Nt

Outputs forever with newlines

Try it online!

KrystosTheOverlord

Posted 2011-01-28T01:49:09.830

Reputation: 681

You don't need the leading 0, which means you can just strip out the teleporters and put a skip at the end instead. Try it online!. You can also do 1:@+:N! for the same amount of bytes if you prefer the stack not filling up

– Jo King – 2019-10-17T00:54:12.563

1

Taktentus, 87 bytes

a:=1
@wy_n:=a
@wy:=32
b:=1
n:=44
@>=n
_:=@stop
@wy_n:=a
@wy:=32
c:=a
a+=b
b:=c
n--
_-=8

n are variable how many times we count (n-1 because first are writing directly)

0x3

Posted 2011-01-28T01:49:09.830

Reputation: 21

1

Scala, 52 chars:

def f(a:Int,b:Int):Int={println(a);f(b,a+b)};f(0,1)

user unknown

Posted 2011-01-28T01:49:09.830

Reputation: 4 210

1

Bash 100

This is a very slow, but hey no performance penalty. First line needed.

#!/bin/bash
if [ $1 -lt 2 ]; then
echo $1; exit; fi
expr `$0 \`expr $1 - 1\`` + `$0 \`expr $1 - 2\``

Alexandru

Posted 2011-01-28T01:49:09.830

Reputation: 5 485

I see the white space surrounding the brackets and instinctively click the "comment" button to tell you it should be removed... then I remember this is bash – Cyoce – 2016-03-25T06:05:04.943

There is redundant whitespace here, after each semicolon. – Peter Cordes – 2016-12-07T15:04:33.013

More a question: You don't need a shebang, do you? See ruby, python and xy-script. – user unknown – 2011-04-12T01:39:20.290

1(($1<2))&& echo $1 && exit;v=$1;p=$0;echo $(($($p $((v-1)))+$($p $((v-2))))) 77 chars with the same approach, just different syntax and a bit faster – user unknown – 2011-04-12T01:50:21.737

solution fails on TIO.run , and so does the version in comments. – roblogic – 2019-08-28T09:20:42.763

1

Befunge 98, 10 characters

1:"]"y+#

8-character code generating the fibonacci sequence on the stack, under the assumption that # should first wrap around then skip, which sadly does not hold in CCBI (where I run my Befunge code). It would work if we restricted the fungespace X dimension to 8 cells.

1#;:"]"y+;

Using 10 characters, the code actually works in CCBI, generating the sequence on the stack.

1#;:.:"]"y+;

With 12 characters, we have working code that outputs space-delimited numbers to stdout (would be 10 chars if based on the first version).

1#;:.:"]"y+:0`2*k#@;

This 20-character version ends the loop as soon as overflow occurs (on 32bit system, it delivers the sequence up to 1836311903). If you add 2 more characters, each number is on a separate line (insert a, after :.)

All these versions operate purely on the stack, no modification of fungespace cells. The 'printing' versions do so in addition to generating the sequence on the stack.

Breakdown:

  1. 1 pushes 1 on the empty stack.
  2. # skips the next fungespace cell (;).
  3. :. duplicates, pops and prints the top-of-stack value (1 in the first iteration). Inserting a, here outputs an ASCII 10 character, which makes a new line.
  4. : duplicates again. (Stack now [1 1])
  5. "]" pushes 93 (ASCII). This is explained further below. (Stack now [1 1 93])
  6. y pops a value and pushes system information for it. In our case, that's the third-of-top value on the stack. In the first iteration, this is 0, as there are only two elements there. (Stack now [1 1 0])
  7. + pops two values and pushes their sum. (Stack now [1 1])
  8. :0' compares the TOS value with 0 and pushes 1 if it was greater, else 0. (It should be a backtick.) (Stack now [1 1 1])
  9. 2*k# pops and doubles our comparison result, and performs the # that many times (0 or 2). While the numbers are positive, it skips to the ;, otherwise to the @ (because k automatically moves the IP beyond its target with a 0 argument). (Stack now [1 1])
  10. @ terminates the program. It is only reached when overflow occurred.
  11. ; creates kind of a wormhole. It skips everything until it encounters another ;, which it will at the third character of the line. Execution continues with step 3.)

In step 5.), I use 93 as an argument to y. This value is individual, because y outputs things like the command line arguments and environment variables, and starts returning values from the stack (top-down) if its argument is greater than the size of actual system information y emits. If eg. you rename the script to a different length name, you have to adjust this value.

To find the correct value, you can insert 01-y (which pushes ALL system information) at the beginning, start in the debugger (-t switch for CCBI), step 4, see how big your stack is, add 3, and replace ] with the resulting character.

Note that the use of y may cause CCBI to report an Access violation on @ which can be safely ignored, as is the case on my system (Win8.1/64, ccbi.exe/32). The short versions keep on looping into eternity (given infinite memory).

PS: If we move the :. between the y and +, the printed sequence becomes 0 1 1 2 ... If we want it starting with 0 on the stack, we simply insert 0 at the beginning (and leave :. where it is now).

Paul Thomann

Posted 2011-01-28T01:49:09.830

Reputation: 346

1

CHIP 8

Not so short but displays the fibonacci sequence on screen:

00E06600690060006101221E3900120E8200801081206F00810489F0120A6500830064F083428336833683368336F32900E0D56575088300640F8342F329D56500EE

without displaying on screen:

00E06000610182008010812081041206

Number23

Posted 2011-01-28T01:49:09.830

Reputation: 11

1

Ruby, 27

What, no Ruby answers?

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

Prints each number, starting correctly with the first two 1s, to STDOUT ad infinitum (VERY QUICKLY from irb in my environment - you've been warned). I've been learning Ruby lately, so I figured I'd contribute this. If it can be shortened in any way, let me know.

Kasran

Posted 2011-01-28T01:49:09.830

Reputation: 681

1

Element, 12 (option two) or 11 (option one)

I've decided to go back in time and answer some classic golfing questions with Element to give it some more street cred.

The following code prints out the Fibonacci sequence continuously (it overflows rather quickly). Each number is printed separately, although there is no whitespace separation.

1!{4:`~2@+}
1            push 1 onto the stack
 !           flip the empty control stack to 1 to enable looping
  {       }  infinite while loop
  {4:     }  have 4 copies (3 additional) of the newest number on the stack
  {  `    }  output one copy
  {   ~   }  A fancy way to get zero from a copyusing the variable retrieval function
  {    2~ }  Move one copy from position 0 to position 2 (behind the old number)
  {      +}  add the number to the old number

The following code inputs a number and outputs the Nth number in the sequence (0-indexed).

1_'[3:~2@+]`
1             push a 1
 _'           take input then move it to the control stack
   [      ]   FOR loop
   [3:    ]   make two additional copies of the top number (3 is the total count)
   [  ~   ]   turn one copy into a zero
   [   2@ ]   move from position 0 to position 2, behind the old number
   [     +]   add the old and newer number
           `  output the result 

For completion's sake, here is a link to the interpreter.

PhiNotPi

Posted 2011-01-28T01:49:09.830

Reputation: 26 739

1

Julia - 20 Characters

f=n->([1 1;1 0]^n)[]

I used the same basic algorithm as the Octave answer. This starts with f(0)->1, f(1)->1, to avoid needing an explicit array index. This is 4 characters shorter than the naive recursive algorithm.

f=n->n<2?1:f(n-1)+f(n-2)

Andrew

Posted 2011-01-28T01:49:09.830

Reputation: 301

1

Clojure: 38 chars

    (def f(lazy-cat[0 1](map +(rest f)f)))

run with:

    f

mnicky

Posted 2011-01-28T01:49:09.830

Reputation: 111

1

Python 3, 39 38 bytes

a=1
b=1
while 1:c=a+b;print(c);a=c;b=c

Ungolfed:

a = 1
b = 1
while 1:
    c = a + b
    print(c)
    a = c
    b = c

Is there some way of getting rid of the b=c statement?

m654

Posted 2011-01-28T01:49:09.830

Reputation: 765

Welcome to PPCG! Does a=b=c work in Python? (Same for a=b=1.) Also, do you really need the space after :? – Martin Ender – 2015-10-12T13:26:42.643

@MartinBüttner It did print the Fibonnaci sequence, and it also showed a weird wavy "animation" :P – m654 – 2015-10-12T14:07:54.697

@MartinBüttner Assignments can be chained, just like comparisons, but they don't return a value so you can't do a=1+(b=c). – lirtosiast – 2015-10-12T14:13:34.927

This doesn't print the right sequence. It's not hard to fix though.

– Ørjan Johansen – 2019-01-31T23:03:43.740

1

Rust, 44 bytes

fn f(n:u8)->u8{if n<2{n}else{f(n-1)+f(n-2)}}

jus1in

Posted 2011-01-28T01:49:09.830

Reputation: 81

1

Forth, 27 bytes

Prints them forever (until it exceeds the maximum integer).

: f over . 2dup + recurse ;

Try it online

Returns the nth Fibonacci number. This assumes I can leave garbage on the stack (the result is still on top), 30 bytes:

: f 1 0 rot 0 DO 2dup + LOOP ;

Try it online

mbomb007

Posted 2011-01-28T01:49:09.830

Reputation: 21 944

1

dc, 29 chars

1ddppsa[+sblalbsalbplxx]sxlxx

user46200

Posted 2011-01-28T01:49:09.830

Reputation:

Verified. how the $^*# does that work?? – roblogic – 2019-08-28T09:04:22.167

1

Burlesque, 8 bytes

Update: With current WIP one can use 1J2q?+C~.

Shortest way to produce [fib(0)..fib(n)] without trashing the stack (14B):

{0 1q?+#RC!}RS

Explanation

There's the concept of "Continuation" in Burlesque which basically means that you run a function on a stack without destroying the stack. Fibonacci is the perfect example use-case for what these continuations are good for. If you have a program like 1 1 add then this results in a stack of 2 because add destroys the data. If add were not to destroy the data the stack would look like 1 1 2 and if we just do 1 1 add add it would look like 1 1 2 3. So all we need to do to generate a Fibonacci sequence is to call add n-times without popping the arguments. A continuation takes a snapshot of the stack, runs the function, pops the result from the stack, reverts the stack to the snapshot and pushes the result of the function to it. C! is the Burlesque built-in for "run this continuation n-times". However, doing so would trash our stack (which is no problem if you just want to print out Fibonacci numbers). Otherwise we need to use the RS built-in which runs a function in a different stack environment. RS takes a value as an argument, creates an empty stack, pushes that value to it and then runs the given function on that stack and after the function has run it will collect that stack into a list and push that list to the main stack. #R rotates the stack because the stack layout will look like N 0 1 but we need that N because it's the argument for C! so we rotate the stack. q?+ is just shorthand for {?+} (q wraps the next token into a block).

If you don't care about trashing the stack you just drop the RS:

blsq ) 10 0 1q?+#R!C
0
1
1
2
3
5
8
13
21
34
55
89

Try it online here.

Shortest way to produce fib(n) as a reusable non stack-trashing piece of code I can think of is (17B):

0 1{Jx/?+}#RE!jvv

Older Stuff

There's dozens of ways to do that. These push the fibonacci numbers to the stack:

blsq ) 0 1{#s2.+++}10E!
blsq ) 0 1q?+10C!

However, the snippets above will also trash your stack. Alternatives for that are either:

blsq ) 0 1{Jx/?+}10E!jvv

which just computes the 10th fibonacci number. Also by still using continuations you can let the whole thing run in a seperate stack environment like uhm so:

blsq ) {10}{0 1q?+#RC!}rs
{89 55 34 21 13 8 5 3 2 1 1 0}
blsq ) 10{0 1q?+#RC!}RS
{89 55 34 21 13 8 5 3 2 1 1 0}

Really depends on your needs.

mroman

Posted 2011-01-28T01:49:09.830

Reputation: 1 382

This is [tag:code-golf], so please post the shortest solution you can find with its byte count. – lirtosiast – 2015-10-22T17:20:30.267

1

Vitsy, 11 Bytes

I'm certain there's a way to shorten these.

Print out all fibonacci (to Integer.MAX_VALUE)

01[D}+DNaO]
01          Push 0 and 1 to the stack.
  [       ] Repeat infinitely.
   D        Duplicate the top item of the stack.
    }       Rotate the stack to right.
     +      Add the top two items.
      D     Duplicate the top item.
       N    Print the top item out as a number.
        aO  Print a return.

Print out to input fibonacci (13 bytes):

01}\[D}+DNaO]
01            Push 0 and 1 to the stack.
  }\[       ] Get the input and repeat that many times.
     D        Duplicate the top item of the stack.
      }       Rotate the stack to right.
       +      Add the top two items.
        D     Duplicate the top item.
         N    Print the top item out as a number.
          aO  Print a return.

Addison Crump

Posted 2011-01-28T01:49:09.830

Reputation: 10 763

1

Minkolang 0.10, 10 bytes

This language was created after this challenge but not for it.

Stream (link, do not click "Run"):

01d1R+dN2@

A mite clever, if I do think so. The 2@ at the end is a 2-trampoline that jumps over the 01 at the beginning, allowing the sequence to rise unabated.

Nth Fibonacci (link):

01nd,7&[d1R+]rN.

Worse than I expected, 16 bytes. 01 sets it up, nd,7&...N. prints out 0 if the input is 0 and does the loop otherwise. [d1R+] builds up the sequence, then r reverses the stack and the correct number is outputted and the program ends with N..

El'endia Starman

Posted 2011-01-28T01:49:09.830

Reputation: 14 504

Grar! Again? You beat me by one again. grumble – Addison Crump – 2015-10-30T20:26:43.260

.... ¯\(ツ) – El'endia Starman – 2015-10-30T20:38:28.033

1

Pip, 10 9 bytes

(The language is newer than the question.)

W1o:y+YPo

Outputs infinite Fibonacci numbers on separate lines, beginning with 1. Try it online!

Explanation

The easy part is W1, which uses 1 as an always-truthy condition to create an infinite while loop.

We use two built-in variables, o and y, which are initially 1 and "", respectively. Note that an empty string in arithmetic contexts is treated as 0. At each iteration, y will hold the smaller of two consecutive Fibonacci numbers, and o will hold the larger.

The loop body is a single expression: o:y+YPo. It's important to know that Pip evaluates a binary-operator expression by first evaluating the left operand, then the right operand, then performing the operation. So, using the third iteration as an example (y is 1, o is 2):

  • The left operand of : (the assignment operator) is o; we'll compute y+YPo and then assign that value to o.
  • The left operand of + is y, which is currently 1.
  • The right operand of + is YPo. YP is a unary operator that takes the value of its operand--here, o, which is 2--prints it, and yanks it into y. So when YPo is evaluated, 2 is printed, y is set to 2, and the expression evaluates to 2.
  • + adds 1 and 2 and gives 3.
  • : assigns 3 to o.

The end result is that 2 is printed, y becomes 2, and o becomes 3. Repeat ad infinitum.

DLosc

Posted 2011-01-28T01:49:09.830

Reputation: 21 213

1

Turing machine code, 389

I wrote this the other day and decided to post it. Generates an infinite Fibonacci sequence in unary on the tape. See a commented version in action here.

0 _ 1 r 1
1 _ _ r 2
2 _ 0 r 3
3 _ _ r 4
4 _ 0 l 5
5 0 * l 5
5 _ * l 5
5 1 * r f
a 0 1 r b
b 0 * r b
b _ * r c
c 0 * r c
c _ * r d
d _ 0 l e
e 0 * l e
e _ * l e
e 1 * r f
f 0 1 r g
f _ * r k
g 0 * r g
g _ * r h
h 0 * r h
h _ * r i
i 0 * r i
i _ 0 l j
j 0 * l j
j _ * l j
j 1 * r f
k 0 1 r l
k _ * l R
l 0 * r l
l _ * r m
m 0 * r m
m _ 0 l n
n 0 * l n
n _ * l n
n 1 * r k
R _ * r a
R 1 0 l R

DLosc

Posted 2011-01-28T01:49:09.830

Reputation: 21 213

1

ShapeScript, 16 14 bytes

_1@0@'@1?+'*!#

This reads an integer n (in unary) from STDIN and prints the nth Fibonacci number.

The submission is non-competing, since this challenge predates ShapeScript's creation by a few years.

Try it online!

How it works

        Input: a string of n 1's 
_       Get the length of the input to push n.
1@      Swap it with 1 (F[-1]).
0@      Swap it with 0 (F[0]).
        STACK: F[-1]   F[0]   n
'       Push a string that, when evaluated for the i-th time,
        does the following:
  @       Swap F[i-2] on top of F[i-1].
  1?      Push a copy of F[i-1].
  +       Add the copy of F[i+1] to F[i].
'       STACK: F[i-1]   F[i]
*!      Repeat the string n times and evaluate it.
#       Discard F[n] from the stack.

Dennis

Posted 2011-01-28T01:49:09.830

Reputation: 196 637

1

Binary-Encoded Golfical, 27+1 (-x flag)=28 bytes

Noncompeting, language postdates the question.

Hexdump:

00 90 02 00 01 14 0C 01 14 00 00 14 1B 1E 08 01
14 2C 17 0A 01 3A 0C 01 2D 1C 1D

This encoding can be converted back to the original image using the github repo's included Encoder utility (java Encoder d "<encoded file>" "<target file>") or run directly by adding the -x flag

Original image:

enter image description here

Magnified 50x:

enter image description here

Rough translation:

*p=1;
*(p+1)=*p;
*p=0;
while true:
 p++;
 push *p;
 p--;
 *(p+1)=*p;
 *p=pop;
 *p+=*(p+1);
 print *p;
end while;

SuperJedi224

Posted 2011-01-28T01:49:09.830

Reputation: 11 342

1

beeswax, 12 bytes (sequence), 42 bytes (n-th Fib.)

Beeswax is newer than the question, so no competition here.

Fibonacci sequence.

p{N<P{*
>~+d

No promotion to higher bit widths implemented in my solution, so 64-bit overflow starts at the 93rd or 92nd Fibonacci number, depending if you start counting your sequence at 0 or 1:

0  
1  
1  
2  
3  
5  
8  
13 
21 
34 
55 
89 
.
.
.
4660046610375530309
7540113804746346429
12200160415121876738   ← 93rd Fibonacci number
1293530146158671551    ← 1st. 64-bit overflow/wraparound
13493690561280548289

N-th Fibonacci number:

;{#'<>~P~L#MM@>+@'p@{;
  _TNX~P~K#{; d~@M<

The same limit applies to this solution.

M L

Posted 2011-01-28T01:49:09.830

Reputation: 2 865

1

C, 224 229 227 chars

...prints the n'th fibonacci or 2^n

Golfed up:

#import <Foundation/Foundation.h>
typedef unsigned long long f;f main(int c,char*v[]){f n=strtoull(v[1],(char**)v[2],10)-1;f x=(c>2&&++n==0)?0:1;f y=0;while(n--!=0&&x+y>=x&&x>0){f z=x;c>2?x+=y=z:(x+=y,y=z);}printf("%llu\n",x);}

Readable:

#import <Foundation/Foundation.h>
typedef unsigned long long f;
f main(int c,char*v[]){
    f n=strtoull(v[1],(char**)v[2],10)-1;
    f x=(c>2&&++n==0)?0:1;
    f y=0;
    while(n--!=0&&x+y>=x&&x>0){
        f z=x;
        c>2?x+=y=z:(x+=y,y=z);
    }
    printf("%llu\n",x);
}

If the number exceeds the length of an unsigned long long it will print the highest it can get. Return type is f (unsigned long long) for short code, it does generate 2 compiler warnings and a note but it still compiles!

It also has the option to calculate 2^n because it initially printed that.

Usage:

  • ./fibbin 42 - prints 42'th fibonacci number (267914296)
  • ./fibbin 42 anyInputHere - prints 2^n (4398046511104).

Don't enter values of 0, higher than 93 (fibonacci) or higher than 63 (2^n).

Examples:

  • ./fibbin 1 = 1
  • ./fibbin 2 = 1
  • ./fibbin 3 = 2
  • ./fibbin 4 = 3
  • ./fibbin 42 = 267914296
  • ./fibbin 92 = 7540113804746346429
  • ./fibbin 93 = 12200160415121876738 - this is the highest i can go
  • ./fibbin 94 = should be 19740274219868223167, but it doesn't fit into an unsigned long long so i will print #93

  • ./fibbin 1 bin - 2

  • ./fibbin 2 bin - 4
  • ./fibbin 3 bin - 8
  • ./fibbin 4 bin - 16
  • ./fibbin 42 bin - 4398046511104
  • ./fibbin 62 bin - 4611686018427387904
  • ./fibbin 63 bin - 9223372036854775808 - this is the highest i can go
  • ./fibbin 64 bin - should be 18446744073709551616, but it doesn't fit into an unsigned long long so i will print 0

These tests match the output of wolfram-alpha, due to the heavy calculations wolfram may time out but it generally doesn't.

x13

Posted 2011-01-28T01:49:09.830

Reputation: 180

I'm no C expert but I think n--!=0&&... can be replaced with n--&&... – Cyoce – 2016-05-02T15:17:54.123

1

Brainf*ck, 489 466 characters

Granted, this is a bit overkill, not to mention that it could be optimised a lot. I will get to improving it tomorrow, since it's too late today.

EDIT: Improved by a few bytes by putting stuff closer together on the tape.

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

(With added newlines for readability)

takra

Posted 2011-01-28T01:49:09.830

Reputation: 793

1

PlatyPar, 7 bytes

0A1wAC+

Try it online!

Explanation:

0A1       ## push first two Fibonacci numbers to stack and print them
    w     ## while last item != 0 (always true)
     A      ## print the most recently calculated Fibonacci number
      C+    ## push the sum of the last two items of the stack

This one is a sequence.

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

1

Detour, 20 bytes

This one is going for the "infinite sequence" option.

v1vq:$
  $+
p,p^
^ q

Try it online!

Branch 1 takes a number, prints it, adds it with the number from Branch 2, then puts the result in Branch 2
Branch 2 takes a number, feeds it to the addition with branch 1 then puts the original number (not the sum) in Branch 1.

For a better explanation click the link and you'll see it in action.

More "readable" version:

Detour, 267 bytes

:$v  1v   q   # split into branches

          +   # push sum of last 2 fibonacci numbers to branch 2
      {  

  p , p   ^   # print branch 1, merge with branch 3

      }

  ^   q       # push branch 2 into branch 1 for printing and recycling

# 1   2   3

Try it online!

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

1

Oration, 135 bytes

I believe that this is "optimal"... takes a deep breath here we go!

Inhale
Start a function f with n
If n<2
Return n
Backtracking
Inhale
Here
Literally, f(n-2)+f(n-1)
I'm done
Listen
Invoke f with number

The little ~> is input. This outputs the (input)th Fibonacci number. This transpiles to (in Python):

def f(n):
    if n<2:
        return  n
    return f(n-2)+f(n-1) 
print(f(eval(input("~>"))))

Conor O'Brien

Posted 2011-01-28T01:49:09.830

Reputation: 36 228

1Why is the transpiled Python code not golfed D: – Downgoat – 2016-02-02T04:01:12.700

1

Oracle SQL 9.2, 80 bytes

SELECT ROUND(POWER((1+SQRT(5))/2,LEVEL-1)/SQRT(5))FROM DUAL CONNECT BY LEVEL<:1;

Jeto

Posted 2011-01-28T01:49:09.830

Reputation: 1 601

1

Lua, 51 bytes

function f(n) return n<2 and n or f(n-1)+f(n-2)end

It creates a function called f(n), that takes an input (n). If n = 1, returns n. This function uses recursion.

TheCrimulo

Posted 2011-01-28T01:49:09.830

Reputation: 21

1

Perl 5, 23 bytes

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

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

Hat tip.

msh210

Posted 2011-01-28T01:49:09.830

Reputation: 3 094

1

CJam, noncompeting, 11 bytes

0X{_@+}q~*;

A Simmons

Posted 2011-01-28T01:49:09.830

Reputation: 4 005

F(0) = 0. You should eliminate the backslash. – Dennis – 2016-03-02T15:40:40.617

Ah I was assuming that we were starting from 1,1..... so I guess this is a good convention since it saves a byte :) – A Simmons – 2016-03-02T16:18:55.513

People start the Fibonacci sequence at different values, so F(0) = 0 may or may not be defined. However, when it comes to indexing, F(1), F(2) = 1, since a lot of the sequence's properties depend on that. – Dennis – 2016-03-02T16:29:39.690

1

DUP, 10 bytes

1$[^^+2!]!

Try it here.

An infinite stream that leaves results on stack. Use the Step button to avoid setting off the infinite loop.

Explanation

1$         {start w/ 2 1's}
  [     ]! {execute lambda}
   ^^      {take top 2 items on stack}
     +     {add them}
      2!   {self recurse!}

Mama Fun Roll

Posted 2011-01-28T01:49:09.830

Reputation: 7 234

1

Gogh, 10 bytes

¹Ƥ{Ƥ÷®+Ø}x

Executed from the command line like this:

$ ./gogh "" "¹Ƥ{Ƥ÷®+Ø}x"

Explanation

¹       “ Push two ones to the stack.                 ”
Ƥ       “ Print the TOS.                              ”
{       “ Open a code block.                          ”
 Ƥ      “ Print the TOS.                              ”
 ÷      “ Duplicate the TOS.                          ”
 ®      “ Rotate the stack leftward.                  ”
 +      “ Destructively add the TOS to the STOS.      ”
 Ø      “ Loop all preceding code (within the block). ”
}       “ Close a code block.                         ”
x       “ Execute the TOS.                            ”

Zach Gates

Posted 2011-01-28T01:49:09.830

Reputation: 6 152

1

Scratch, 106 characters

This isn't impressive at all but someone had to do it.

scratch blocks

when gf clicked
add[1]to[f v
forever
 add((item[last v]of[f v])+(item((length of[f v])-(1))of[f v]))to[f v

scratchblocks2 render

Fairly bog-standard solution. "f" is a list which starts off empty. Runs as long as you let it.

Since it's not easy to define what is and isn't a "character" in Scratch I've used the forum plugin's formatting. This allows me to cheat off some additional characters (scratchblocks2 is very lenient with dropping closing parenthesis, "end"s, and shaving off whitespace here and there)

quat

Posted 2011-01-28T01:49:09.830

Reputation: 1 211

1

Cy, 11 + 1 (-p flag) = 12 bytes (non-competing)

This is going for the infinite stream

0 1 $&+ &do

(the -p flag implicitly prints every non-block value pushed to the stack)

Literally,

  • push 0
    • print it
  • push 1
    • print it
  • forever
    • push the sum of the last two items
    • print it



Without the -p flag semi-cheat:

Cy, 24 bytes

0 &:< 1 &:< {&+ &:<} &do

Cyoce

Posted 2011-01-28T01:49:09.830

Reputation: 2 690

1

Alpax, 5 bytes (non-competing)

Non-competing since the language postdates the challenge. Code:

⇇+
1¹

Yes, that's right mates. My newest invention, which is more mathematically based than 05AB1E. This language uses a lot of recursion, so be aware. This is a bit like a stack based language, but a little bit different. The elaborated version of the above code is:

a(n) = ⇇+
a(0) = 1, a(1) = 1

Explanation:

⇇ is short for pushing a(n - 1), a(n - 2)
+ adds both functions up.

It then implicitly prints the result of a(n), whereas n is the input.

Uses the Alpax encoding.

Adnan

Posted 2011-01-28T01:49:09.830

Reputation: 41 965

Alpax doesn't exist anymore. – None – 2019-12-24T12:43:25.833

1

Sesos, 11 bytes (non-competing)

Not in-place, linear memory.

Hexdump:

0000000: ae8583 ef6bc7 045fe7 b907                         ....k.._...

Size   : 11 byte(s)

Try it online!

Assembler

set numin
set numout
add 1,rwd 1,get    ;setup tape
jmp
  fwd 1
  jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
  rwd 1
  sub 1
  jmp,sub 1,fwd 1,add 1,rwd 1,jnz
  fwd 1
jnz
fwd 2
put

Leaky Nun

Posted 2011-01-28T01:49:09.830

Reputation: 45 011

1

Java, 71 chars

Single number: (Binet formula, considering 1.62 as the golden ratio))

int f(int n){return(Math.pow(1.62,n)-(Math.pow(-1.62,-n))/Math.sqrt(5)}

I know this isn't surprisingly short, however Math is beautiful and this formula is even more!

ProTheJoker

Posted 2011-01-28T01:49:09.830

Reputation: 11

1

Ruby

Ungolfed, 60 bytes

def fib(prev,nxt)
  x = prev + nxt
  puts x
  fib(nxt,x)
end

Golfed, 33 bytes

def f(a,b)x=a+b;puts x;f(b,x)end

Pretty simple to call, use f(first, next).

XiKuuKy

Posted 2011-01-28T01:49:09.830

Reputation: 369

1

You can still golf it further. Try taking out the unnecessary whitespace. Also, there are some good tips here

– James – 2016-09-12T05:14:26.513

1x=a+b;puts x can become puts x=a+b – Cyoce – 2016-12-11T03:26:39.687

1

Java 8 29 bytes

Using Java 8 lambdas. This is a valid statement if there exists a function interface with a method that returns an int and takes an int as a parameter. Also the variable that stores the lambda must be declared as a member (static or non static) of the class it is in so that it can be used recursively.

f=n->n<2?0:f.f(n-1)+f.f(n-2);

Ungolfed:

@FunctionalInterface interface F
{
    int f(int n);
}

public class Main
{
    static F f;

    public static void main(String[] args)
    {
        f=n->n<2?0:f.f(n-1)+f.f(n-2);
    }
}

BananyaDev

Posted 2011-01-28T01:49:09.830

Reputation: 41

1

Prismatic, 113 bytes (can be smaller)

right wideness wideness left forward up vertex longness backward right vertex tallness forward down vertex vertex

Inspired by Brainfuck, Cubix and Hexagony.

ender_scythe

Posted 2011-01-28T01:49:09.830

Reputation: 249

0

Python, 75 bytes

a=[1,1]
while True:
    a.append(a[-1]+a[-2])
    a.pop(0)
    print(a[-2])

Yes, I know, way too big, but I don't know golfing languages that well.

Juntos

Posted 2011-01-28T01:49:09.830

Reputation: 41

1>

  • while True can be replaced with while 1. 2) You only need one space of indentation. 3) The while loop contents can be replaced with print(a[0]);a=[a[1],sum(a)] (on the same line as the while statement). 4) The parentheses on the print call can be removed if you're using Python 2. With all these tricks applied: a=[1,1]\nwhile 1:print(a[0]);a=[a[1],sum(a)] (replace the '\n' with a literal newline).
  • < – Mego – 2016-11-17T13:41:54.847

    If you take Mego's approach you can replace a=[a[1],sum(a)] with a=a[1],sum(a) to save two bytes. This works because the comma creates an implicit tuple rather than a literal list. – Post Rock Garf Hunter – 2016-11-17T13:56:01.493

    The same can also be done with a=[1,1]. It can be shortened to a=1,1 – Post Rock Garf Hunter – 2016-11-17T14:00:21.527

    0

    Stackish, 12 bytes (non-competing)

    01d\+.qzcl2'
    

    How it works:

    0   Load 0 into stack (stack now 0).
    1   Load 1 into stack (stack now 0,1).
    d   Duplicate last number of stack (stack now 0,1,1).
    \   Swap bottom with top (stack now 1,0,1).
    +   Add last two numbers (stack now 1,1).
    .   Pop to output (stack now 1).
    q   Undo pop (stack now 1,1).
    z   Pause.
    c   Clear screen.
    l2' Jump to 2nd character (d).
    
    d   Duplicate last number of stack (stack now 1,1,1).
    \   Swap bottom with top (stack now 1,1,1).
    +   Add last two numbers (stack now 1,2).
    .   Pop to output (stack now 1).
    q   Undo pop (stack now 1,2).
    z   Pause.
    c   Clear screen.
    l2' Jump to 2nd character (d)
    
    ...
    

    ender_scythe

    Posted 2011-01-28T01:49:09.830

    Reputation: 249

    0

    Ruby (as function) 31 bytes

    ->n{a,b=1,0;n.times{a=b+b=a};b}
    

    G B

    Posted 2011-01-28T01:49:09.830

    Reputation: 11 099

    This is byte-per-byte exactly the same as another answer. – Addison Crump – 2017-01-18T00:28:11.853

    Yes, it was. I commented on the other answer and wrote mine before the original author accepted my suggestion. Now I am only leaving the function, because I could not find any ruby function in 5 randomly-sorted pages of answers. – G B – 2017-01-19T07:13:41.910

    @VoteToClose Duplicate answers are allowed.

    – James – 2017-01-19T07:17:40.743

    My code was mostly stolen from the other answer, with a little improvement (which is now also in the original post), and my answer was written much later. I am leaving the function because I could not find another. – G B – 2017-01-19T07:28:09.173

    0

    MATLAB/Octave, n first numbers, 41 39 chars

    a=0:1;for(i=3:n);a(i)=a(i-2)+a(i-1);end
    

    nrz

    Posted 2011-01-28T01:49:09.830

    Reputation: 243

    0

    Javascript, 27 26 characters

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

    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.

    Martín Canaval

    Posted 2011-01-28T01:49:09.830

    Reputation: 101

    0

    Python 3 (53)

    def f(n):
     l,p=0,1
     while n:n,l,p=n-1,p,l+p
     return l
    

    AMK

    Posted 2011-01-28T01:49:09.830

    Reputation: 506

    43 bytes. – Jonathan Frech – 2018-08-12T17:31:48.803

    0

    Clojure, 46

    (defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))
    

    Although, technically 50 since Clojure requires the recur for pseudo tail call:

    (defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))
    

    Non compressed:

    (defn fib [left right iteration]   
      (if (= 0  iteration)
        left
        (fib right (+ right left)  (- iteration 1))))
    

    Programmin Tool

    Posted 2011-01-28T01:49:09.830

    Reputation: 111

    0

    Haskell: 27 (21) characters

    It almost feels like cheating to use Haskell for something like this. It just prints Fibonacci numbers ad infinitum.

    f=1:scanl(+)1f
    main=print f
    

    And if using GHCi only 21 characters, including two newlines, are necessary:

    Prelude>let f=1:scanl(+)1f
    Prelude>f
    [1,1,2,3,5,8,13,21...
    

    Fors

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 020

    this solution was already posted here. FYI.

    – Will Ness – 2017-11-28T10:49:20.230

    0

    C, 33 bytes

    Recursively calculates the nth fibbonacci number.

    f(n){return n>1?f(n-1)+f(n-2):n;}
    

    Bijan

    Posted 2011-01-28T01:49:09.830

    Reputation: 781

    0

    Mathematica, 32 26 bytes

    -6 bytes thanks to @MartinEnder!

    ±1=±2=1;±n_:=±(n-1)+±(n-2)

    Recursive function, returns nth value in sequence.

    numbermaniac

    Posted 2011-01-28T01:49:09.830

    Reputation: 639

    1You can golf this with prefix notation: f@1=f@2=1;f@n_:=f[n-1]+f[n-2]. And even further by defining an operator instead: ±1=±2=1;±n_:=±(n-1)+±(n-2). – Martin Ender – 2017-03-24T09:57:01.137

    Oh yeah, forgot about prefix notation here. Didn't know about the operator, thanks! – numbermaniac – 2017-03-24T11:06:53.123

    0

    JavaScript (ES6)

    A couple of different ES6 implementations. The first two return the nth Fibonacci number and the third returns an array of the first n Fibonacci numbers. Non-competing, obviously.

    30 bytes

    f=
    
    (n,x=1,y=0)=>!n?y:f(n-1,x+y,x)
    
    console.log(f(10))

    46 bytes

    f=
    
    n=>(x=1,y=0,eval("while(n--)[x,y]=[x+y,x]"),y)
    
    console.log(f(10))

    46 bytes

    f=
    
    n=>(a=[],(f=x=>a[x]=x<2?x:f(--x)+f(--x))(n),a)
    
    console.log(f(10))

    Shaggy

    Posted 2011-01-28T01:49:09.830

    Reputation: 24 623

    0

    Axiom, 113 bytes

    f(n:NNI):NNI==(n=0=>0;n:=n-1;x:=sqrt(5);floor(numeric(((x+1)/(2*x))*((1+x)/2)^n+((x-1)/(2*x))*((1-x)/2)^n)))::INT
    

    code for test and results

    (80) -> [f(i)  for i in 0..20]
       (80)
       [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765]
                                                Type: List NonNegativeInteger
    (81) -> f 100
       (81)  354224848179261915076
                                                        Type: PositiveInteger
    (82) -> f 200
       (82)  280571172992510140037336354957747795525632
                                                        Type: PositiveInteger
    (83) -> f 400
       (83)
      1760236806450139664680709294813170892283658770059881093310828506440687624218_
       31925760
                                                        Type: PositiveInteger
    (84) -> f 800
       (84)
      6928308186422471713609360660466569632290421684876894264783997577258487494487_
       420363654234099779749410573113727333378633545181944038619446626409501657425_
       3135847342735360
                                                        Type: PositiveInteger
    (85) -> f 1500
       (85)
      1355112566856310195162377575526951323656561770431639555079987987810736653460_
       922122221302671882558120755439823360357867711740787668744312284056217232330_
       713983569575833249689158528416736647370129969548463847884661978641646883591_
       466734576231634867107272686298047871451723693301109753896341229444935835304_
       2229054930944
                                                        Type: PositiveInteger
    (86) -> f 2000
       (86)
      4224696333392304878698067179976673472756391964001565086095500593531167791551_
       743662247281607190958887487440686606420026093467732621145548367502217030083_
       858092272596709322168369132666938424515347258074945014044152199085287931830_
       556530989999311940427567701708311778838430925973655760228465275886647451746_
       556255968313014088560151159533857580044154666168801306507492995800168547537_
       206536250047308876795741658264221262020608
    

    RosLuP

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 036

    0

    Axiom, 35 bytes

    a(0)==0;a(1)==1;a(n)==a(n-1)+a(n-2)
    

    above it is one succession defined by Recurrence... Results

    (7) -> [a(i)  for i in 0..20]
       (7)  [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765]
    

    RosLuP

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 036

    ricorrence Recurrence? – MD XF – 2017-09-14T04:20:05.743

    @MDXF thank you for the correction... Good morning – RosLuP – 2017-09-14T09:56:56.617

    0

    Tcl, 71 bytes (function implementation=43, Enter=1, call=27)

    proc F x {expr $x>1?\[F $x-1]+\[F $x-2]:$x}
    while 1 {puts [F [incr i]]}
    

    Try it online!

    Serves both purposes: Has a function F that allows calculate the x'th Fibonacci number. then it is called to show on stdout F applied to the whole range of positive integers.

    sergiol

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 055

    tcl,89: Different approach — iterative. demo — but it does not have a function and fails to represent the first one. – sergiol – 2017-07-08T22:17:26.370

    Failed outgolf; tcl,91 (function implementation=56, Enter=1, call=34): https://tio.run/##K0nO@f@/oCg/WaEkOcfKKjexJCOtNC/ZyspNoUKhOrWioEihWqXCztDeTUOlQtdQUxtMG2laqVTU1nKVZ2TmpCoYKlQXlJYUK0SDlbtpRGfmJRcpZMZqxtYq/P8PAA

    – sergiol – 2017-11-05T17:08:59.360

    You can use less expr as there's a leading one, in escaping evaluation of each 1st brackets code 45B

    – david – 2018-12-16T20:00:38.060

    Thanks @david . I did not know I could do it by escaping [ with \\. I bet I have some more answers I can golf them the way you described. – sergiol – 2018-12-16T20:52:52.200

    0

    Tampio, 107 bytes

    uni on 1 lisättynä 1:een lisättynä yhteenlaskuun sovellettuna unen jäseniin ja unen hännän jäseniin
    

    Explanation:

    uni on 1 lisättynä 1:een lisättynä
    uni =  1 :         1     :
    
    yhteenlaskuun sovellettuna  unen jäseniin ja unen hännän jäseniin
    (+)           `zip`        (uni           ,  tail uni            )
    

    fergusq

    Posted 2011-01-28T01:49:09.830

    Reputation: 4 867

    0

    Implicit, 12 11 bytes

    ]3.(,[+%:]ß
    

    Try it online!

    10 bytes (knock off the ß) if we don't need delimiters. It's not specified in the challenge... TIO

    This is my own (rather simple) method of computing the sequence. Explanation:

    #::.(,[+%:]ß
    #::.            push 0, 0, 1 (push stack length, duplicate twice, increment last one)
        (.......    forever (implicit ¶ at end of program)
         ,           swap top two stack values
          [          pop stack into memory
           +         add top two stack values
            %        print
             :       duplicate top of stack
              ]      push memory to stack
               ß     print a space
    

    In a normal language, say, C, it would look like this:

    int x, y, z;
    x = 0; y = 0; z = 1;
    
    do {
        swap(&y, &z);
        x += y;
        y = x;
        printf("%d ",x);
    } while (1);
    

    Equivalence:

    int x = 0, y = 0, z = 1;   // #::.
    do {                       // (
        swap(&y,&z);           // ,
                               // [ (z is ignored below)
        x += y;                // +
        y = x;                 // :
        printf("%d ",x);       // %ß
                               // ] (z is ignored above)
    } while (1);               // ¶
    

    Here's how the stack looks after each operation that modifies it:

    #  0
    :  0 0
    :  0 0 0
    .  0 0 1
    
    ,  0 1 0
    [  0 1
    +  1
    %  1
    :  1 1
    ]  1 1 0
    
    ,  1 0 1
    [  1 0
    +  1
    %  1
    :  1 1
    ]  1 1 1
    
    ,  1 1 1
    [  1 1
    +  2
    %  2
    :  2 2
    ]  2 2 1
    
    ,  2 1 2
    [  2 1
    +  3
    %  3
    :  3 3
    ]  3 3 2
    
    ,  3 2 3
    [  3 2
    +  5
    %  5
    :  5 5
    ]  5 5 3
    
    ,  5 3 5
    [  5 3
    +  8
    %  8
    :  8 8
    ]  8 8 5
    
    ,  8 5 8
    [  8 5
    +  13
    %  13
    :  13 13
    ]  13 13 8
    
    ,  13 8 13
    [  13 8
    +  21
    %  21
    :  21 21
    ]  21 21 13
    
    ,  21 13 21
    [  21 13
    +  34
    %  34
    :  34 34
    ]  34 34 21
    

    Golf notes:

    • ]3. is shorter than #::. which is shorter than :0::1 which is shorter than :0:0:1.
    • ß is shorter than @32.
    • (... is shorter than :1(;...:1).

    (ß, , and implicit added during the writing of this program.)

    MD XF

    Posted 2011-01-28T01:49:09.830

    Reputation: 11 605

    0

    Pug, 30 bytes

    Without input (infinite)

    -a=b=1
    while 1
     =a
     -b=a+(a=b)
    

    Will produce an output:

    1123581321345589144233377610...
    

    With an output delimiter: 34 bytes

    -a=b=1
    while 1
     =a+" "
     -b=a+(a=b)
    

    Will produce an output:

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

    With HTML as an output delimiter: 31 bytes

    -a=b=1
    while 1
     p=a
     -b=a+(a=b)
    

    Although I doubt this is compliant to the challenge's rules, this will produce:

    <p>1</p>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>5</p>
    <p>8</p>
    <p>13</p>
    <p>21</p>
    <p>34</p>
    <p>55</p>
    ...
    


    With input (as a funcion; finite)

    Without an output delimiter, 47 bytes

    mixin f(n)
     -a=b=1
     while n--
      =a
      -b=a+(a=b)
    

    For an input n=10, for example, it produces:

    11235813213455
    


    Just as it is with the infinite series versions:

    • +4 bytes (+" ") = 51 bytes for a space delimiter
    • +1 byte (p) = 48 bytes for an HTML <p> tag delimiter

    Matheus Avellar

    Posted 2011-01-28T01:49:09.830

    Reputation: 273

    0

    JAVA - 108 characters:

    int[]f={0,1};System.out.println(0);for(int i=0;i<9;i+=2)System.out.printf("%d\n%d\n",f[0]+=f[1],f[1]+=f[0]);
    

    user10766

    Posted 2011-01-28T01:49:09.830

    Reputation:

    If a space is required in the code, it should be included in the character count. – Iszi – 2013-11-27T21:53:29.080

    Alright, I will update it. – None – 2013-11-27T21:57:15.567

    Already fixed it for you - looks like someone approved my edit suggestion. – Iszi – 2013-11-27T22:05:28.037

    That was me - I went to fix it, and found you had already. – None – 2013-11-27T22:06:24.800

    Ah. All good, then. Welcome to [codegolf.se]! – Iszi – 2013-11-27T22:10:39.520

    0

    Momema, 28 bytes

    1 1z0-8*01+*1*00+*1-*0-9 9z1
    

    Try it online! Outputs infinitely with a tab between numbers.

    If no separator between numbers is required, you can save four bytes:

    1 1z0-8*01+*1*00+*1-*0z1
    

    Explanation

                                                         #  a = 0
    1   1       #            [1] = 1                     #  b = 1
    z   0       #  label z0: jump past label z0 (no-op)  #  while true {
    -8  *0      #            output num [0]              #    print a
    1   +*1*0   #            [1] = [1] + [0]             #    b = a + b
    0   +*1-*0  #            [0] = [1] - [0]             #    a = b - a
    -9  9       #            output chr 9                #    print '\t'
    z1          #  label z1: jump past label z0          #  }
    

    Esolanging Fruit

    Posted 2011-01-28T01:49:09.830

    Reputation: 13 542

    0

    Reflections, 93 bytes

         \
    /*\/#  (0:0\
    * 0\_*;(0\/ :(0\
      \     v/#@/_ /
    \  (1/ 1)0)*
            : \\/
            \(1/
    

    Test it!

    Explanation:

    Initialisation

    Executing \*/(1\*/*\0\.

    • * at (5|2) pushes 5×2=10 (\n)
    • (1 moves the newline to stack 1
    • * at (0|2) pushes 0×2=0 (F(-1))
    • * at (1|1) pushes 1×1=1 (F(0))
    • 0 moves these two values to stack 0

    Loop

    Executing v1):\(1/\\0)#/:(0\/_//\*@\0:(0#/\_*;(0\/.

    • 1) pulls the newline from stack 1
    • : duplicates it
    • (1 moves the duplicate to stack 1
    • 0) pulls the last result from stack 0
    • # redefines (0|0)
    • : duplicates the last result
    • (0 moves the duplicate back to stack 0
    • _ at (3|0) converts the last result to a list of digits
    • * at (1|1) pushes 1×1=1
    • @ prints the last result and a newline
    • 0 pulls both values from stack 0
    • : duplicates the top one (newer one)
    • (0 pushes the duplicate back to stack 0
    • # redefines (0|0)
    • _ at (0|1) adds the two values together
    • * at (1|1) pushes 1×1=1
    • ; pops that again
    • (0 pushes the new result to stack 0

    wastl

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 089

    0

    Stax, 2 bytes

    |5
    

    Run and debug online!

    Added for completeness. An internal that returns 0-indexed Fibonacci number.

    Infinite sequence generator without using the internal:

    ò¶AÄ∟
    

    The ASCII equivalent is

    01WQb+
    

    Weijun Zhou

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 396

    0

    SmileBASIC, 28 bytes

    F.,1DEF F X,Y?Y
    F Y,X+Y
    END
    

    Ungolfed:

    F 0,1
    DEF F X,Y
     PRINT Y
     F Y,X+Y
    END
    

    12Me21

    Posted 2011-01-28T01:49:09.830

    Reputation: 6 110

    0

    Elixir, 49 bytes

    Defines a function to get the nth fibonacci number. 1-indexed (starts at 0).

    Simple recursive formula. Slow.

    def f(n)when n<2,do: n
    def f(n),do: f(n-1)+f(n-2)
    

    Try it online!

    Elixir, 50 bytes

    Returns an infinite stream of fibonacci numbers. 1-indexed (starts at 0).

    Fast, carries over an accumulator with the sum of the previous two numbers.

    fn->Stream.unfold{0,1},fn{a,b}->{a,{b,a+b}}end end
    

    Try it online!

    Okx

    Posted 2011-01-28T01:49:09.830

    Reputation: 15 025

    0

    Javascript, 57 bytes

    _=1;i=0;for(z=10;z--;)alert((a=>!(o=_+i)+(i=_)+!(_=o))())

    77Tigers

    Posted 2011-01-28T01:49:09.830

    Reputation: 11

    0

    Python 2, 33 31 bytes

    i=j=1
    while 1:print j;i,j=j+i,i
    

    Try it online!

    Uses a loop to infinitely print the sequence. Will eventually error out due to integer overflow. It has been pointed out to me that Python uses arbitrary precision integers. Learn something new every day!

    Triggernometry

    Posted 2011-01-28T01:49:09.830

    Reputation: 765

    1Python uses arbitrary precision integers so an integer overflow will not occur. – Jonathan Frech – 2018-08-03T14:48:19.723

    i,j=1,1 can be i=j=1. – Jonathan Frech – 2018-08-03T14:48:48.127

    0

    µ6, 16 bytes

    [>#[,.[+.]][[,>[#/0[+/1]<>]]/1]]
    

    Try it online!

    Explanation

    [>                               -- right element of the tuple generated by
      #                              -- | primitive recursive function
                                     -- | base case:
       [,                            -- | | pair of
         .                           -- | | | constant zero
         [+.]                        -- | | | successor of constant zero
       ]                             -- | | : (0,1)
                                     -- | recursive case:
       [                             -- | | compose the two
        [,                           -- | | | pair of
         >                           -- | | | | the right element
         [#/0[+/1]<>]                -- | | | | add left & right element
        ]                            -- | | | (snd, fst + snd)
        /1                           -- | | | second argument (we only need the tuple)
       ]                             -- | : (f (n-1), f (n-2) + f (n-1))
    ]                                -- : f n
    

    ბიმო

    Posted 2011-01-28T01:49:09.830

    Reputation: 15 345

    0

    Julia 0.6, 19 bytes

    !a=round(φ^a/√5)
    

    Try it online!

    This is 16 chars and 19 bytes, a goof way to abuse Julia beats the existing Julia answers which were 20 bytes. by 1 bytes and 3 chars

    Muhammad Salman

    Posted 2011-01-28T01:49:09.830

    Reputation: 2 361

    0

    Little Man Computer, 45 bytes, 8 instructions

    Note: both answers only work up to \$ f(15) = 987 \$, as the maximum value for an integer in LMC is \$ 999 \$.

    The first solution generates Fibonacci numbers 'indefinitely':

    LDA 7
    ADD 8
    STA 7
    SUB 8
    STA 8
    OUT
    BRA 0
    DAT 1
    

    and is assembled into RAM as

    507 108 307 208 308 902 600 001
    

    86 bytes, 14 instructions

    The second solution returns the Fibonacci number at the index given (0-based indexing):

    INP
    STA 0
    LDA 12
    ADD 14
    STA 12
    SUB 14
    STA 14
    LDA 0
    SUB 13
    BRP 1
    LDA 14
    OUT
    DAT 1
    DAT 1
    

    ...which is assembled into RAM as:

    901 300 512 114 312 214 314 500 213 801 514 902 001 001
    

    You can test these on the online simulator here.

    FlipTack

    Posted 2011-01-28T01:49:09.830

    Reputation: 13 242

    0

    R, 37 bytes

    Prints the n'th term using the closed form.

    https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

    function(n,s=5^.5)round((s/2+.5)^n/s)
    

    Try it online!

    J.Doe

    Posted 2011-01-28T01:49:09.830

    Reputation: 2 379

    0

    C# (.NET Core), 68, 56 bytes

    Lambda using decimal size for single n.

    EDIT: Ty Jo King for pointing out better ways to assign the maths to the vars!

    p=>{decimal a=0,b=1,j=0;for(;j++<p;b=a-b)a+=b;return a;}
    

    Try it online!

    Destroigo

    Posted 2011-01-28T01:49:09.830

    Reputation: 401

    1

    I don't know much about C++, but 56 bytes

    – Jo King – 2019-01-11T23:47:23.270

    note that there's already a way shorter answer, and that's including a (partial, at least) signature – ASCII-only – 2019-01-18T03:11:36.363

    0

    \/\/>, 9 bytes

    :@+1}:nau
    

    Outputs infinitely starting from 0, with each number on a new line.

    Explanation:

    :           Dupe top of stack
     @          Rotate the top three elements
      +         Add the top two elements
       1}       Push a 1 to the bottom of the stack
         :nau   Print the top number with a trailing newline  
    

    Jo King

    Posted 2011-01-28T01:49:09.830

    Reputation: 38 234

    0

    33, 7 bytes

    1c[oca]
    

    Not a Fibonacci number, I'm afraid.

    TheOnlyMrCat

    Posted 2011-01-28T01:49:09.830

    Reputation: 1 079

    0

    Golfscript 42 bytes

    ~:n;2 -1?:h;5h?:f;1f+2/:p;p n?-1p*n~)?-f/
    

    I origionally solved this in python with 64chars because i didn't think golfscript supported floats. I did some more digging and it actually does if you raise a number to -1.

    Back in my graph theory/combinitorics class we went over creating an O(1) form of recurance eqautions, the fibonacci sequence is one example we used. I don't remeber the method for converting a recurance equation to constant time because the class was a few years ago, but I found the solution for the fibonacci equation online

    constant time fibonacci sequence

    phi

    This allows you to compute the nth fibbonacci number without computing the previous terms

    wade king

    Posted 2011-01-28T01:49:09.830

    Reputation: 109

    You're correct, hardcoing phi is a bit messy, see my updated answer using golfscript and not hardcoding any values – wade king – 2019-08-28T23:53:25.560

    0

    8086/8088 machine code, 8 bytes

    The machine code is on the left; the middle column is disassembly and the rightmost column is an explanation.

    40      ; inc ax          set ax to 1
    41      ; inc cx          set cx to 1
    ef      ; out [dx], ax    output ax to port [dx] (that is, port 0)
    03 c1   ; add ax, cx      set ax to ax + cx
    91      ; xchg ax, cx     exchange ax with cx
    eb fa   ; jmp -4          jump to "out [dx], ax"
    

    Assumptions:

    • The registers AX, CX and DX are initially 0.
    • A number may be output by writing it as a word to port 0.

    This runs forever, outputting the Fibonacci numbers modulo \$2^{16}\$ = 65,536, starting with 1, 1.

    Tanner Swett

    Posted 2011-01-28T01:49:09.830

    Reputation: 531

    0

    Oasis, 2 bytes

    Answer to the open exercise on the Oasis repo.

    +T
    

    Explanation

    Expanded program:

    bc+10
    

    When + requires 1 parameter, it tries to calculate a(n-1). For the other parameter, it tries to calculate a(n-2). (Hence the expansion.)

    In addition, the T instruction expands to 10 in the program, which are the base test cases (a(0) is 0. a(1) is 1. Since base test cases are popped from the end before the Oasis program is executed in reverse.)

    TIO

    user85052

    Posted 2011-01-28T01:49:09.830

    Reputation:

    0

    C (gcc), 57 bytes

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

    Try it online!

    Duarte Arribas

    Posted 2011-01-28T01:49:09.830

    Reputation: 273

    Shouldn't you be starting at 1,1,2,3...? Also, you can omit the =0, and instead of for(;;), you can call main() again. Try it online!

    – Jo King – 2019-10-21T04:41:54.080

    1

    @ceilingcat And even further (assuming no arguments) 45 bytes

    – Jo King – 2019-10-21T20:31:25.393

    or 41 bytes with a different interpreter

    – Jo King – 2019-10-21T21:31:33.433

    0

    tq, 6 bytes

    Currently this has no separator...

    01p+r)
    

    Explanation

    0,        # Initialize the number 0
      1,      # (Since a preceding 0 in decimal is disallowed)
        p+r,  # Initialize the third item in the list as the 
              # previous item + the previous-previous item
            ) # Extend this forever
    

    user85052

    Posted 2011-01-28T01:49:09.830

    Reputation:

    0

    JVM Byte Code, 79 bytes

    The byte count given is for a complete class file that defines a class Code containing single static method Code which implement Fibonacci. A hex dump of the file is given below.

    0000000: cafe babe 0003 002d 0004 0100 0428 4929  .......-.....(I)
    0000010: 4901 0004 436f 6465 0700 0200 2000 0300  I...Code.... ...
    0000020: 0000 0000 0000 0100 0800 0200 0100 0100  ................
    0000030: 0200 0000 1800 0400 0100 0000 0c03 045a  ...............Z
    0000040: 6084 00ff 1a9d fffa ac00 0000 0000 00    `..............
    

    A helper class is required to invoke the function.

    class Test {
        public static void main(String[] args){
            for(int i = 0; i < 20; i++){
                System.out.println(Code.Code(i));
            }
        }
    }
    

    Try it online!


    The disassembly of the class file with javap -c shows actual byte code implementation of Fibonacci. This requires only 11 bytes, the rest of the 79 bytes in the class file are various header tables that can't be omitted.

    class Code {
      static int Code(int);
        Code:
           0: iconst_0
           1: iconst_1
           2: dup_x1
           3: iadd
           4: iinc          0, -1
           7: iload_0
           8: ifgt          2
          11: ireturn
    }
    

    ankh-morpork

    Posted 2011-01-28T01:49:09.830

    Reputation: 1 350

    0

    C 64 Characters

    a;main(f,n){scanf("%d",&n);while(--n)f+=a=f-a;printf("%d",f-a);}
    

    This will print the nth Fibonacci number.

    A more readable format :

    a;
    main(f,n){
    scanf("%d",&n);
    while(--n)
       f+=a=f-a;
    printf("%d",f-a);
    }
    

    DollarAkshay

    Posted 2011-01-28T01:49:09.830

    Reputation: 103

    0

    JavaScript (ES6) - 24 Characters (non-competing)

    f=x=>x<3?1:f(x-1)+f(x-2)
    

    JavaScript - 24 Characters (snippet)

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

    Set a value for n and it will calculate the nth Fibonacci value.

    MT0

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 373

    1The JavaScript ES6 version should be non-competing as JavaScript ES6 was implemented after this challenge. – Downgoat – 2016-03-25T01:07:06.123

    1Also, the second solution is invalid as it's a snippet and not a full program / function. – Downgoat – 2016-03-25T01:10:55.830

    0

    F#, 63 chars:

    let rec g x y n=if n=x then x else f (n-1) y (x+y)
    let f=g 0 1
    

    MarcinJuraszek

    Posted 2011-01-28T01:49:09.830

    Reputation: 101

    0

    ~-~! (No Comment) - 27

    '=|*>~[<'&*-~>+<'&*-~~>]*|:
    

    Didn't think it'd be this short.

    cjfaure

    Posted 2011-01-28T01:49:09.830

    Reputation: 4 213

    0

    TI-BASIC - 18 symbols

    to print fibonacci sequence starting from 0:

    ;i
    ;While 1
    ;Disp real(Ans
    ;real(Ans)+imag(Ans)+ireal(Ans
    ;End
    

    to print fibonacci sequence starting from 1:

    ;1
    ;While 1
    ;Disp real(Ans
    ;real(Ans)+imag(Ans)+ireal(Ans
    ;End
    

    averykhoo

    Posted 2011-01-28T01:49:09.830

    Reputation: 101

    real(Ans)-conj(iAns is shorter. – lirtosiast – 2015-08-08T04:23:51.500

    0

    C / Objective-c, 62

    c;f(a,b){printf("%d ",a+b);if(c++<40)f(a+b,a);}main(){f(0,1);}
    

    This will print the first 40 fibonacci numbers. I assume the compiler will set c=0. If it is trash, than it will not work;

    This version is smaller, but it infite show all sequence number

    C / Objective-c, 50 (infinite)

    f(a,b){printf("%d ",a+b);f(a+b,a);}main(){f(0,1);}
    

    Rodrigo

    Posted 2011-01-28T01:49:09.830

    Reputation: 101

    0

    Python (56 chars)

    n=input()
    x=5**0.5
    print ((1+x)**n-(1-x)**n)/((2**n)*x)
    

    And for the sequence

    n=input()
    i=1
    x=5**0.5
    while i<=n:
        print ((1+x)**i-(1-x)**i)/((2**i)*x)
        i+=1
    

    elssar

    Posted 2011-01-28T01:49:09.830

    Reputation: 579

    0

    PHP, Finite - 46 chars

    <?for($b=1;$i++<$n;)echo$b-$a=($b+=$a)-$a,"
    ";
    

    where $n is the length of the sequence

    PHP, Infinite - 39 chars

    <?for($b=1;;)echo$b-$a=($b+=$a)-$a,"
    ";
    

    Cameron

    Posted 2011-01-28T01:49:09.830

    Reputation: 9

    0

    Ruby - 49 characters

    Nobody has done a Ruby solution for the second problem so I thought I'd give that a go:

    p Hash.new{|h,k|k<2?k:(h[k-2]+h[k-1])}[gets.to_i]
    

    dav_i

    Posted 2011-01-28T01:49:09.830

    Reputation: 121

    0

    Javascript, 53 bytes

    a=[1,1];setInterval('a.push(a[b=a.length-1]+a[b-1])')
    

    I decided to use a new approach to create an infinite stream. Works anywhere else but Firefox.

    To get the array of integers, simply do a from the console.

    Mama Fun Roll

    Posted 2011-01-28T01:49:09.830

    Reputation: 7 234

    0

    R - 39

    Shortest - recursive, until SO:

    f=function(i,j){cat(i);f(j,i+j)};f(1,1)
    

    Until n:

    i=j=1;for(x in 1:n){print(i);k=i;i=i+j;j=k}
    

    or (a bit vectorized):

    a=c(1,1);for(x in 1:n)print((a=c(a[2],sum(a)))[1])
    

    or (without any loop or recursion):

    a=c(1,1);sapply(1:n,function(i)a<<-c(a[2],sum(a)))[1,]
    

    lambruscoAcido

    Posted 2011-01-28T01:49:09.830

    Reputation: 401

    0

    CoffeeScript, 63 bytes

    j=0;k=1;a=[];a=((i=j+k;k=j;j=i) for i in [0..prompt()]);alert a
    

    username.ak

    Posted 2011-01-28T01:49:09.830

    Reputation: 411

    0

    C, 45 bytes

    Simple, iterative approach. Exits when signed integer overflows.

    a;main(b){for(;b>0;printf("%d ",a=b-a))b+=a;}
    

    Try it here.

    Cole Cameron

    Posted 2011-01-28T01:49:09.830

    Reputation: 1 013

    I seems to me you can remove b>0 condition. – sergiol – 2017-07-08T22:32:08.277

    0

    Pylons, 13 bytes

    Takes the number of iterations as a command line argument to the interpreter.

    11fA..+@{A,i}
    

    How it works:

    11  # Pushes 1, 1 to the stack.
    fA#.##.#+@  # Creates a function "A" that takes the top two elements of the stack and adds them.
    {A,i}  # Calls A sys.argv[1] times.
    

    Morgan Thrapp

    Posted 2011-01-28T01:49:09.830

    Reputation: 3 574

    0

    Julia, 20 bytes

    !n=n>1?!~-n+!~-~-n:n
    

    Straightforward implementation of the recursive definition. No match for the matrix approach, but a lovely opportunity to abuse Julia's ability to redefine operators.

    Try it online!

    Dennis

    Posted 2011-01-28T01:49:09.830

    Reputation: 196 637

    0

    Maple, 27 bytes

    ifelse(n<3,1,f(n-1)+f(n-2))
    

    Usage:

    > f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
    > f(2);
      1
    > f(3);
      2
    

    DSkoog

    Posted 2011-01-28T01:49:09.830

    Reputation: 560

    0

    Ouroboros, 10 bytes

    Outputs an infinite Fibonacci sequence, starting at 0, separated by newlines.

    .!+.@.nao+
    

    Explanation

    Each line of an Ouroboros program represents a snake eating its own tail. When execution reaches the end of the line, it loops back to the beginning. Each snake has a stack to store values.

    If this is the first pass through the code, we need to initialize the stack by turning the top into a 1. (The empty stack is treated as containing infinite zeros.) .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value. This has the effect of pushing a 1 if the stack was empty, and doing nothing if the stack contained a nonzero value.

    Now, call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. a pushes 10 and o outputs it as a character (printing a newline). Finally, + adds x to a copy of y. The stack now contains y and x+y, and we proceed to the next iteration.

    Try it out

    // Define Stack class
    function Stack() {
      this.stack = [];
      this.length = 0;
    }
    Stack.prototype.push = function(item) {
      this.stack.push(item);
      this.length++;
    }
    Stack.prototype.pop = function() {
      var result = 0;
      if (this.length > 0) {
        result = this.stack.pop();
        this.length--;
      }
      return result;
    }
    Stack.prototype.top = function() {
      var result = 0;
      if (this.length > 0) {
        result = this.stack[this.length - 1];
      }
      return result;
    }
    Stack.prototype.toString = function() {
      return "" + this.stack;
    }
    
    // Define Snake class
    function Snake(code) {
      this.code = code;
      this.length = this.code.length;
      this.ip = 0;
      this.ownStack = new Stack();
      this.currStack = this.ownStack;
      this.alive = true;
      this.wait = 0;
      this.partialString = this.partialNumber = null;
    }
    Snake.prototype.step = function() {
      if (!this.alive) {
        return null;
      }
      if (this.wait > 0) {
        this.wait--;
        return null;
      }
      var instruction = this.code.charAt(this.ip);
      var output = null;
      console.log("Executing instruction " + instruction);
      if (this.partialString !== null) {
        // We're in the middle of a double-quoted string
        if (instruction == '"') {
          // Close the string and push its character codes in reverse order
          for (var i = this.partialString.length - 1; i >= 0; i--) {
            this.currStack.push(this.partialString.charCodeAt(i));
          }
          this.partialString = null;
        } else {
          this.partialString += instruction;
        }
      } else if (instruction == '"') {
        this.partialString = "";
      } else if ("0" <= instruction && instruction <= "9") {
        if (this.partialNumber !== null) {
          this.partialNumber = this.partialNumber + instruction;  // NB: concatenation!
        } else {
          this.partialNumber = instruction;
        }
        next = this.code.charAt((this.ip + 1) % this.length);
        if (next < "0" || "9" < next) {
          // Next instruction is non-numeric, so end number and push it
          this.currStack.push(+this.partialNumber);
          this.partialNumber = null;
        }
      } else if ("a" <= instruction && instruction <= "f") {
        // a-f push numbers 10 through 15
        var value = instruction.charCodeAt(0) - 87;
        this.currStack.push(value);
      } else if (instruction == "$") {
        // Toggle the current stack
        if (this.currStack === this.ownStack) {
          this.currStack = this.program.sharedStack;
        } else {
          this.currStack = this.ownStack;
        }
      } else if (instruction == "s") {
        this.currStack = this.ownStack;
      } else if (instruction == "S") {
        this.currStack = this.program.sharedStack;
      } else if (instruction == "l") {
        this.currStack.push(this.ownStack.length);
      } else if (instruction == "L") {
        this.currStack.push(this.program.sharedStack.length);
      } else if (instruction == ".") {
        var item = this.currStack.pop();
        this.currStack.push(item);
        this.currStack.push(item);
      } else if (instruction == "m") {
        var item = this.ownStack.pop();
        this.program.sharedStack.push(item);
      } else if (instruction == "M") {
        var item = this.program.sharedStack.pop();
        this.ownStack.push(item);
      } else if (instruction == "y") {
        var item = this.ownStack.top();
        this.program.sharedStack.push(item);
      } else if (instruction == "Y") {
        var item = this.program.sharedStack.top();
        this.ownStack.push(item);
      } else if (instruction == "\\") {
        var top = this.currStack.pop();
        var next = this.currStack.pop()
        this.currStack.push(top);
        this.currStack.push(next);
      } else if (instruction == "@") {
        var c = this.currStack.pop();
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(b);
        this.currStack.push(c);
        this.currStack.push(a);
      } else if (instruction == ";") {
        this.currStack.pop();
      } else if (instruction == "+") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(a + b);
      } else if (instruction == "-") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(a - b);
      } else if (instruction == "*") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(a * b);
      } else if (instruction == "/") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(a / b);
      } else if (instruction == "%") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(a % b);
      } else if (instruction == "_") {
        this.currStack.push(-this.currStack.pop());
      } else if (instruction == "I") {
        var value = this.currStack.pop();
        if (value < 0) {
          this.currStack.push(Math.ceil(value));
        } else {
          this.currStack.push(Math.floor(value));
        }
      } else if (instruction == ">") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(+(a > b));
      } else if (instruction == "<") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(+(a < b));
      } else if (instruction == "=") {
        var b = this.currStack.pop();
        var a = this.currStack.pop();
        this.currStack.push(+(a == b));
      } else if (instruction == "!") {
        this.currStack.push(+ !this.currStack.pop());
      } else if (instruction == "?") {
        this.currStack.push(Math.random());
      } else if (instruction == "n") {
        output = "" + this.currStack.pop();
      } else if (instruction == "o") {
        output = String.fromCharCode(this.currStack.pop());
      } else if (instruction == "r") {
        var input = this.program.io.getNumber();
        this.currStack.push(input);
      } else if (instruction == "i") {
        var input = this.program.io.getChar();
        this.currStack.push(input);
      } else if (instruction == "(") {
        this.length -= Math.floor(this.currStack.pop());
        this.length = Math.max(this.length, 0);
      } else if (instruction == ")") {
        this.length += Math.floor(this.currStack.pop());
        this.length = Math.min(this.length, this.code.length);
      } else if (instruction == "w") {
        this.wait = this.currStack.pop();
      }
      // Any unrecognized character is a no-op
      if (this.ip >= this.length) {
        // We've swallowed the IP, so this snake dies
        this.alive = false;
        this.program.snakesLiving--;
      } else {
        // Increment IP and loop if appropriate
        this.ip = (this.ip + 1) % this.length;
      }
      return output;
    }
    Snake.prototype.getHighlightedCode = function() {
      var result = "";
      for (var i = 0; i < this.code.length; i++) {
        if (i == this.length) {
          result += '<span class="swallowedCode">';
        }
        if (i == this.ip) {
          if (this.wait > 0) {
            result += '<span class="nextActiveToken">';
          } else {
            result += '<span class="activeToken">';
          }
          result += escapeEntities(this.code.charAt(i)) + '</span>';
        } else {
          result += escapeEntities(this.code.charAt(i));
        }
      }
      if (this.length < this.code.length) {
        result += '</span>';
      }
      return result;
    }
    
    // Define Program class
    function Program(source, speed, io) {
      this.sharedStack = new Stack();
      this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
        var snake = new Snake(snakeCode);
        snake.program = this;
        snake.sharedStack = this.sharedStack;
        return snake;
      }.bind(this));
      this.snakesLiving = this.snakes.length;
      this.io = io;
      this.speed = speed || 10;
      this.halting = false;
    }
    Program.prototype.run = function() {
      this.step();
      if (this.snakesLiving) {
        this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
      }
    }
    Program.prototype.step = function() {
       for (var s = 0; s < this.snakes.length; s++) {
        var output = this.snakes[s].step();
        if (output) {
          this.io.print(output);
        }
      }
      this.io.displaySource(this.snakes.map(function (snake) {
          return snake.getHighlightedCode();
        }).join("<br>"));
     }
    Program.prototype.halt = function() {
      window.clearTimeout(this.timeout);
    }
    
    var ioFunctions = {
      print: function (item) {
        var stdout = document.getElementById('stdout');
        stdout.value += "" + item;
      },
      getChar: function () {
        if (inputData) {
          var inputChar = inputData[0];
          inputData = inputData.slice(1);
          result = inputChar.charCodeAt(0);
        } else {
          result = -1;
        }
        var stdinDisplay = document.getElementById('stdin-display');
        stdinDisplay.innerHTML = escapeEntities(inputData);
        return result;
      },
      getNumber: function () {
        while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
          inputData = inputData.slice(1);
        }
        if (inputData) {
          var inputNumber = inputData.match(/\d+/)[0];
          inputData = inputData.slice(inputNumber.length);
          result = +inputNumber;
        } else {
          result = -1;
        }
        var stdinDisplay = document.getElementById('stdin-display');
        stdinDisplay.innerHTML = escapeEntities(inputData);
        return result;
      },
      displaySource: function (formattedCode) {
        var sourceDisplay = document.getElementById('source-display');
        sourceDisplay.innerHTML = formattedCode;
      }
    };
    var program = null;
    var inputData = null;
    function showEditor() {
      var source = document.getElementById('source'),
        sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
        stdin = document.getElementById('stdin'),
        stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
      
      source.style.display = "block";
      stdin.style.display = "block";
      sourceDisplayWrapper.style.display = "none";
      stdinDisplayWrapper.style.display = "none";
      
      source.focus();
    }
    function hideEditor() {
      var source = document.getElementById('source'),
        sourceDisplay = document.getElementById('source-display'),
        sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
        stdin = document.getElementById('stdin'),
        stdinDisplay = document.getElementById('stdin-display'),
        stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
      
      source.style.display = "none";
      stdin.style.display = "none";
      sourceDisplayWrapper.style.display = "block";
      stdinDisplayWrapper.style.display = "block";
      
      var sourceHeight = getComputedStyle(source).height,
        stdinHeight = getComputedStyle(stdin).height;
      sourceDisplayWrapper.style.minHeight = sourceHeight;
      sourceDisplayWrapper.style.maxHeight = sourceHeight;
      stdinDisplayWrapper.style.minHeight = stdinHeight;
      stdinDisplayWrapper.style.maxHeight = stdinHeight;
      sourceDisplay.textContent = source.value;
      stdinDisplay.textContent = stdin.value;
    }
    function escapeEntities(input) {
      return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
    function resetProgram() {
      var stdout = document.getElementById('stdout');
      stdout.value = null;
      if (program !== null) {
        program.halt();
      }
      program = null;
      inputData = null;
      showEditor();
    }
    function initProgram() {
      var source = document.getElementById('source'),
        stepsPerSecond = document.getElementById('steps-per-second'),
        stdin = document.getElementById('stdin');
      program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
      hideEditor();
      inputData = stdin.value;
    }
    function runBtnClick() {
      if (program === null || program.snakesLiving == 0) {
        resetProgram();
        initProgram();
      } else {
        program.halt();
        var stepsPerSecond = document.getElementById('steps-per-second');
        program.speed = +stepsPerSecond.innerHTML;
      }
      program.run();
    }
    function stepBtnClick() {
      if (program === null) {
        initProgram();
      } else {
        program.halt();
      }
      program.step();
    }
    function sourceDisplayClick() {
      resetProgram();
    }
    .container {
        width: 100%;
    }
    .so-box {
        font-family:'Helvetica Neue', Arial, sans-serif;
        font-weight: bold;
        color: #fff;
        text-align: center;
        padding: .3em .7em;
        font-size: 1em;
        line-height: 1.1;
        border: 1px solid #c47b07;
        -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
        text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
        background: #f88912;
        box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
    }
    .control {
        display: inline-block;
        border-radius: 6px;
        float: left;
        margin-right: 25px;
        cursor: pointer;
    }
    .option {
        padding: 10px 20px;
        margin-right: 25px;
        float: left;
    }
    h1 {
        text-align: center;
        font-family: Georgia, 'Times New Roman', serif;
    }
    a {
        text-decoration: none;
    }
    input, textarea {
        box-sizing: border-box;
    }
    textarea {
        display: block;
        white-space: pre;
        overflow: auto;
        height: 100px;
        width: 100%;
        max-width: 100%;
        min-height: 25px;
    }
    span[contenteditable] {
        padding: 2px 6px;
        background: #cc7801;
        color: #fff;
    }
    #stdout-container, #stdin-container {
        height: auto;
        padding: 6px 0;
    }
    #reset {
        float: right;
    }
    #source-display-wrapper , #stdin-display-wrapper{
        display: none;
        width: 100%;
        height: 100%;
        overflow: auto;
        border: 1px solid black;
        box-sizing: border-box;
    }
    #source-display , #stdin-display{
        font-family: monospace;
        white-space: pre;
        padding: 2px;
    }
    .activeToken {
        background: #f93;
    }
    .nextActiveToken {
        background: #bbb;
    }
    .swallowedCode{
        color: #999;
    }
    .clearfix:after {
        content:".";
        display: block;
        height: 0;
        clear: both;
        visibility: hidden;
    }
    .clearfix {
        display: inline-block;
    }
    * html .clearfix {
        height: 1%;
    }
    .clearfix {
        display: block;
    }
    <!--
    Designed and written 2015 by D. Loscutoff
    Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
    -->
    <div class="container">
    <textarea id="source" placeholder="Enter your program here" wrap="off">.!+.@.nao+</textarea>
    <div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
    <textarea id="stdin" placeholder="Input" wrap="off"></textarea>
    <div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
    <span id="steps-per-second" contenteditable>20</span></div></div>

    DLosc

    Posted 2011-01-28T01:49:09.830

    Reputation: 21 213