129
\$\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\$
1
  • 2
    \$\begingroup\$ I am sort of waiting for a response like "f", 1 byte, in my math based golf language. \$\endgroup\$ – Zsolt Szilagy Aug 11 '20 at 11:57

278 Answers 278

1
6
7
8 9 10
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\$

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

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

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!

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

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.

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

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

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

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!

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

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

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

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

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ – Loovjo Sep 23 '18 at 15:06
1
\$\begingroup\$

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.

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

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.

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

Python 3, 43 Bytes

a,c=0,0;b=1
while 1:print(a);c=a+b;a=b;b=c
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Note 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. \$\endgroup\$ – FlipTack Dec 17 '18 at 20:21
  • \$\begingroup\$ Also, 0 isn't supposed to be included in this challenge. \$\endgroup\$ – Ørjan Johansen Dec 18 '18 at 1:30
1
\$\begingroup\$

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

Awk, 35 bytes

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

Try it online

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

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
\$\endgroup\$
1
  • \$\begingroup\$ This loses precision at only n=71, outputting 308061521170130 instead of 308061521170129 \$\endgroup\$ – Jo King Jul 26 '19 at 4:58
1
\$\begingroup\$

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

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!

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

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                                      Ŕ@Í€
\$\endgroup\$
1
\$\begingroup\$

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

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!

\$\endgroup\$
1
  • \$\begingroup\$ An interesting (very slow) 12-byter, 0-indexed but wrong on element 0: {ḃ₁~clᵐ⌉<3}ᶜ \$\endgroup\$ – Unrelated String Nov 20 '19 at 23:45
1
\$\begingroup\$

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.

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

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

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

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

\$\endgroup\$
1
6
7
8 9 10

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.