111
\$\begingroup\$

The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are both 1.

Here are the first few terms

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

Write the shortest code that either:

  • Generates the Fibonacci sequence without end.

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

You may use standard forms of input and output.

(I gave both options in case one is easier to do in your chosen language than the other.)


For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.


Leaderboard

/* Configuration */

var QUESTION_ID = 85; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 3; // This should be the user ID of the challenge author.

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

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

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

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

table thead {
  font-weight: bold;
}

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

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

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

\$\endgroup\$

224 Answers 224

1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

Braingolf, 23 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ 17 bytes \$\endgroup\$ – Skidsdev Jun 16 '17 at 9:20
  • \$\begingroup\$ 14 bytes \$\endgroup\$ – Skidsdev Jun 16 '17 at 9:23
  • \$\begingroup\$ 8 bytes for output the nth number \$\endgroup\$ – Skidsdev Jun 16 '17 at 9:35
1
\$\begingroup\$

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

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

\$\endgroup\$
  • \$\begingroup\$ Note current version uses Z and Y instead of z and y \$\endgroup\$ – Stephen Feb 1 at 4:54
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Joy, 28 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Husk, 7 2 bytes (non-competing)

İf

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Polyglot with ES6. \$\endgroup\$ – Zacharý Aug 12 '17 at 21:54
  • \$\begingroup\$ @Zacharý Huh that's cool. This is weird; Proton is often a polyglot with Python too :P \$\endgroup\$ – HyperNeutrino Aug 13 '17 at 0:51
1
\$\begingroup\$

PHP, 39 bytes

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

Try it online!

Explanation

<?php

An infinite loop is started. The zero-th term in the series, initially $a, is 0, so needn't be assigned. $b is initially the second term and so is set to 1.

for ($b = 1;;) 

The part which does all the work is echo $a = -$a + $b += $a, ' ';. Here it is expanded.

{

Calculate the new value for $b: the next term is the sum of the previous two.

    $b = $b + $a;

$a needs to be moved on one term as well. It is calculated by subtracting itself from the new value of $b.

    $a = $b - $a;

For byte-saving convenience, it is $a that is echoed each time—followed by a space!

    echo $a, ' ';
}
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I'm no C expert but I think n--!=0&&... can be replaced with n--&&... \$\endgroup\$ – Cyoce May 2 '16 at 15:17
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

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

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

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]

\$\endgroup\$
1
\$\begingroup\$

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

Brain-Flak, 36 bytes

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

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

Try it online!

Explanation coming soon...

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

FALSE, 13 bytes

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

Numbers are pushed to the stack.

\$\endgroup\$
1
\$\begingroup\$

Japt, 3 bytes

Just to add to the collection.

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

MgU

Try it

\$\endgroup\$
1
\$\begingroup\$

><>, 11 bytes

10r:n:@+aor

Try it online!

Prints the Fibonacci sequence forever, separated by newlines.

\$\endgroup\$
1
\$\begingroup\$

Coconut, 28 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Whitespace, 50 47

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

SSSLSSSTLSLSTLSTLSSSLSLSSTSSTSLTSSSSLSTLSTLSLSL

Explanation:

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

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

1123581321345589144233377610987159725844181676510946...

(Thanks to @KevinCruijssen for -3 bytes.)

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

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

\$\endgroup\$

Your Answer

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

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