151
\$\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, in accordance to the standard rules:

  • Generates the Fibonacci sequence without end.

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

  • Given n calculates the first n terms of the sequence

You may use standard forms of input and output.


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


Leaderboard

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

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

\$\endgroup\$
5
  • 6
    \$\begingroup\$ I am sort of waiting for a response like "f", 1 byte, in my math based golf language. \$\endgroup\$ Commented Aug 11, 2020 at 11:57
  • \$\begingroup\$ @ChrisJesterYoung can we use 1.0 are 1 only? \$\endgroup\$ Commented May 11, 2022 at 2:45
  • \$\begingroup\$ @NumberBasher 1.0 is fine. \$\endgroup\$ Commented May 20, 2022 at 19:10
  • \$\begingroup\$ What about 1.3? \$\endgroup\$ Commented Aug 28, 2022 at 15:10
  • 3
    \$\begingroup\$ Am I allowed to start the sequence with 0, 1? \$\endgroup\$ Commented Oct 11, 2022 at 3:41

354 Answers 354

1
4 5
6
7 8
12
2
\$\begingroup\$

dc, 21 17 bytes

0z[dp_3R+lmx]dsmx

Try it online!

This prints the Fibonacci sequence endlessly.



My previous (21-byte) version accepted an input \$n\$ on stdin, outputting the \$n^\text{th}\$ Fibonacci number on stdout (1-indexed):

9k5v1+2/?^5v/.5+0k1/p

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

International Phonetic Esoteric Language, 28 bytes

<f>/b1ɨʌʟ|e|1zb1z<f>d<fib>s|e|\

A function that expects a number \$n \ge 0\$ to be on the stack, and leaves the \$n\$-th Fibonacci number.

Explanation:

<f>/ (n1 -- n2) (where n2 is the n1-th fibonacci number)
         (check for case n=1)
b        (dup)
 1       (push 1)
  ɨ      (n>1?)
   ʌ     (skip if n>1)
    ʟ⟨e⟩ (if n<=1, jump to end label)
1                (push 1)
 z               (subtract)
  b              (dup)
   1             (push 1)
    z            (subtract)
     <f>         (recurse)
        d        (swap)
         <f>     (recurse)
            s    (add)
             ⟨e⟩ (end label)
\
\$\endgroup\$
2
\$\begingroup\$

R, 33 32 bytes

CAUTION: This attempts to print the whole Fibonacci sequence. It does not stop.

a=b=1;repeat print(a<-(b=b+a)-a)

Pretty simple. Initialize a and b. Then a repeat loop which adds them to find the next number and print it. This loop will not stop, though eventually the overflow means it just prints NaN repeatedly.

Edit: saved 1 byte by switching to a=b=1 which required a different loop control mechanism to print the first few values, and then a different assignment location, etc.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 25 bytes by using T and F as variables. \$\endgroup\$ Commented May 21, 2022 at 15:39
  • 1
    \$\begingroup\$ 23 bytes by using T and F as variables, and additional inspiration from Giuseppe... \$\endgroup\$ Commented May 26, 2022 at 21:22
  • 1
    \$\begingroup\$ As far as I'm concerned, those are sufficient improvements you should submit them independently. Really like them by the way \$\endgroup\$ Commented Jun 2, 2022 at 1:29
2
\$\begingroup\$

Flurry, 46 bytes

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

How to run:

$ target/Flurry -nin -c "{}{<{}{<[<>{}]{{}[<><<>()>]}>}>}{{}{{}}{{}}}()" 8
34

It doesn't use the stack at all (except for fetching the input number from the pre-populated stack). Instead, it uses pure functional construction developed by Anders Kaseorg in my SKI golf challenge.

one = \f. \x. f x
    = I
    = {{}}

one-pair = \f.f one one
         = {{}{{}}{{}}}

succ = \n. \f. \x. f (n f x)
     = \n. \f. S (\x. f) (n f)
     = \n. S (\f. S (K f)) n
     = S (S . K)
     = <><<>()>

next-pair-helper = \f. \m. \n. f n (m succ n)
                 = \f. \m. S f (m succ)
                 = \f. S f ∘ (\m. m succ)
                 = {<[<>{}]{{}[<><<>()>]}>}

next-pair = \p. \f. p (next-pair-helper f)
          = \p. p ∘ next-pair-helper
          = {<{}{<[<>{}]{{}[<><<>()>]}>}>}

fib = {} next-pair one-pair K
    = {}{<{}{<[<>{}]{{}[<><<>()>]}>}>}{{}{{}}{{}}}()
\$\endgroup\$
2
\$\begingroup\$

Arn, 5 bytes

Since I finally implemented sequences in my interpreter this is now a valid submission :)

╔Tò”7

Explained

Unpacked: [1 1{+

[ Sequence...
  1 1 ...with 2 values initialized at 1...
  { ...the rest of which are determined by the block...
    + ...that adds the top two values
  } Implied, can be removed
] Implied, can be removed

Since Arn supports infinite sequences and BigNums, this will continuously output fibonacci numbers infinitely (hypothetically)

\$\endgroup\$
2
+100
\$\begingroup\$

Barrel, 26 bytes

Disclaimer: The language is newer than the question, but I didn't even think of golfing this until after I'd created the language. I did update the language after I originally wrote the answer, and changed my answer, but that was because I was fixing the interpreter and made some changes to the spec to make the language work better. I wasn't cheating, I promise :)

+&1:0¤n &0:@1&1:a#@0+←1

Explanation:

+                          // set the accumulator to one by incrementing (initialization)
 &1:0                      // set register 1 to value 0 (initialization)
     ¤               ←1   // define a target that can be jumped to; then, jump to the previously defined jump target
      n                    // print the accumulator as a number and implicitly print the following space
        &0:@1              // set register 0 to register 1
             &1:a          // set register 1 to the value of the accumulator
                 #         // for as many times...
                  @0       //     ... as [value of register 0]...
                    +      //         ... increment the accumulator

I find it a bit hard to explain this further, so here's a rough chart of the accumulator and the two registers used during execution which will hopefully remove any confusion:

acc   reg[0]    reg[1] |
---------------------- |
1     <uninit>  0      | initialize; print acc("1")
1     0         1      | set reg[0] to reg[1]; set reg[1] to acc
1     0         1      | add reg[0] to acc; jump back and print acc ("1")
1     1         1      | set reg[0] to reg[1]; set reg[1] to acc
2     1         1      | add reg[0] to acc; jump back and print acc ("2")
2     1         2      | set reg[0] to reg[1]; set reg[1] to acc
3     1         2      | add reg[0] to acc; jump back and print acc ("3")
3     2         3      | set reg[0] to reg[1]; set reg[1] to acc
5     2         3      | add reg[0] to acc; jump back and print acc ("5")
5     3         5      | set reg[0] to reg[1]; set reg[1] to acc
8     3         5      | add reg[0] to acc; jump back and print acc ("8")

...and so forth and so on.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Added the bounty! Also, you don't need the disclaimer, there used to be a rule banning languages newer than the challenge but it was removed a while back :) \$\endgroup\$ Commented Apr 14, 2021 at 1:52
2
\$\begingroup\$

Pinecone, 35 bytes

b:0;a:1;tru@(print:a;t:a;a:a+b;b:t)

Competitive Pinecone answer!

\$\endgroup\$
2
  • \$\begingroup\$ How did you get to know Pinecone? For me it was because I wanted to learn how to make my own language \$\endgroup\$ Commented Apr 21, 2021 at 16:14
  • \$\begingroup\$ @ophact I was researching on creating Lexers, and I found an article on it, that's how i reached there :) \$\endgroup\$ Commented Apr 21, 2021 at 16:15
2
\$\begingroup\$

Red, 47 bytes

F: func[N][either N < 2[n][(F N - 2)+ F N - 1]]

Try it online!

First red answer. Modified from the solution on this page.

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

Grok, 16 bytes

1z1j
wYZlYp2yp+9

Try it Online!

Prints an infinite, tab-separated sequence. (Tabs instead of spaces/newlines since they are golfier.) The 5 flag is just so it times out faster.

Explanation:

1z           # Print the initial 1
  1          # Push 1 to the stack
   j         # Start the IP moving down
   l         # Start the IP moving right
    Yp       # Get the last number on the stack
      2yp    # Get the number before that (initially 0)
         +   # Add them together
w         9  # Print a Tab
 YZ          # Print the next number without popping it
\$\endgroup\$
2
\$\begingroup\$

Lua, 40 36 bytes

Prints the infinite Fibonacci sequence. Saved 4 bytes by using a goto operator instead of a while loop.

i,j=0,1::a::j,i=i,i+j print(i)goto a

Try it online!

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

LOLCODE, 262 bytes

HAI 1
I HAS A x
GIMMEH x
x IS NOW A NUMBR
BOTH SAEM x 0
O RLY?
YA RLY
VISIBLE "0"
NO WAI
I HAS A a ITZ 0
I HAS A b ITZ 1
I HAS A c ITZ 0
IM IN YR l UPPIN YR i WILE BOTH SAEM i SMALLR OF i DIFF OF x 2
c R SUM OF a b
a R b
b R c
IM OUTTA YR l
VISIBLE b
OIC
KTHXBYE

Reads n from STDIN and returrns the nth Fibonacci number.

Try it online!

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

Nim, 38 bytes

var a,b=1
while 1>0:a=b-a;echo a;b+=a

Attempt This Online!

Nim, 64 bytes, with arbitrary precision

import bigints
var a,b=initBigInt(1)
while 1>0:a=b-a;echo a;b+=a

Attempt This Online!

Thanks to @JoKing and @cairdcoinheringaahing

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Can you golf true to 1 and temp to c? \$\endgroup\$ Commented Jun 28, 2021 at 22:32
  • 1
    \$\begingroup\$ You can also golf the declaration to var a,b=1 if you then change the update section to a=b-a;echo a;b+=a. You can also update the true part to be 1>0 like in your arbitrary precision code \$\endgroup\$ Commented Jun 29, 2021 at 4:33
  • \$\begingroup\$ Right thanks, stupid of me to leave it like that. \$\endgroup\$ Commented Jun 30, 2021 at 1:35
2
\$\begingroup\$

BitCycle -u, 67 45 bytes

v1<   <
BvC1Av
v~~v <
>  Cv>^
   v~~
  \>101!

Try it online!

It's beautiful... I have some idea of how this works.

The A, B and C are collectors. when the field is empty, the first non-empty collector (sorting in alphabetical order) has all collectors opened.

The basic idea is that the two numbers are stored in the B and A collectors. On each iteration:

  • The bits stored in A are emitted into the main C collector
  • The bits stored in B are duplicated and sent to the main C collector, and the C collector next to the A collector. This is necessary because otherwise the A collector would open before the C collector.
  • Both C collectors open. One emits its bits into A (previously stored in B).
  • The other duplicates its bits, and sends one stream to the B collector and the other stream to an output device
  • Duplicating bits also emits negated bits. one of these (a 0) from the B collector is sent to the output device via the \

This is because integer outputt in BitCycle is done in unary, with a sequence of n 1s and then a 0. a 0 must be sent before the next iteration begins.

The 101 is initially emitted to the output device to print 1, 1 (the 0 to print the next 1 is supplied before the 2 is emitted).

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

Factor + benchmark.fib3, 3 bytes

fib

Try it online!

And a non- built-in version:

Factor, 32 bytes

[ 0 1 rot [ tuck + ] times nip ]

Try it online!

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

GeoGebra, 38 bytes

n
InputBox(n
Iteration(p+q,p,q,{0,1},n

Input in Input Box. Outputs the nth term of the 0-indexed Fibonacci sequence starting at \$F_0=0\$, \$F_1=1\$.

Try It On GeoGebra!

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

Husk, 7 2 bytes

İf

Try it online!

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

Python 33 bytes

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

This will be an infinite loop!


Python 31 bytes

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
\$\endgroup\$
4
  • 3
    \$\begingroup\$ The loop for your "31 char" program would need to be included in the score. \$\endgroup\$ Commented Nov 4, 2016 at 15:00
  • \$\begingroup\$ ^^ also, we usually give the count in bytes, not characters. \$\endgroup\$ Commented Dec 28, 2016 at 12:25
  • \$\begingroup\$ +1 love the first solution! Can you explain what f.func_defaults[0][0] in your 2nd solution does? \$\endgroup\$ Commented Nov 1, 2022 at 10:52
  • \$\begingroup\$ @DialFrost i'm a year late, but f.func_defaults[0] is a reference to a (the first default argument of f), so f.func_defaults[0][0] gives the first item of a. \$\endgroup\$ Commented Dec 26, 2023 at 11:46
2
\$\begingroup\$

Nibbles, 4.5 bytes (9 nibbles)

.~~1+<2
.~~         # append until null (here this means forever)
   1        # starting with 1
    +       #   sum of
     <2     #   take 2 elements (or 1 if there's only 1)

enter image description here


Nibbles also supports a recursive approach to calculate the n-th element:
``; $ -$2 1 + @-$2 @-$~ (10 bytes = 20 nibbles)

``;                      # define a recursive function:
    $                    # initial input is arg1;
      -$2                # when input minus 2 is zero or negative:
          1              # return 1;
                         # otherwise:
            +            # add together
              @-$2       # recursive call with input minus 2
                   @-$~  # and recursive call with input minus 1

...although simply indexing into the infinite sequence is shorter: =$.~~1+<2 (5 bytes = 10 nibbles).

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

ForWhile, 11 bytes

{1'[';+:).}

takes number n on stack as input, returns nth Fibonacci number

online interpreter

Explanation

{         }  \ anonymous procedure
 1'          \ push 1 below argument
   [   :)    \ repeat n times
    '        \ swap the top two values on the stack  (A B -> B A)
     ;       \ copy the lower value above the higher value (B A -> B A B)
      +      \ add the op two stack elements  (B A B-> B A+B)
         .   \ discard the top stack element (only return one Fibonacci number)
\$\endgroup\$
2
\$\begingroup\$

ELF executable (x64), 194 bytes

This is my first non-trivial assembly program, so there may be still room for improvement

hexdump:

457f 464c 0102 0301 0000 0000 0000 0000
0002 003e 0001 0000 0078 0040 0000 0000
0040 0000 0000 0000 0000 0000 0000 0000
0000 0000 0040 0038 0001 0040 0000 0000
0001 0000 0007 0000 0000 0000 0000 0000
0000 0040 0000 0000 0000 0040 0000 0000
00c2 0000 0000 0000 0142 0000 0000 0000
1000 0000 0000 0000 ff48 50c0 e853 0007
0000 5b58 0148 ebd8 48f2 c6c7 0141 0040
3148 b3db 880a b21e 4001 d788 3148 48d2
f3f7 8640 40d7 c780 4830 ceff 8840 fe3e
48c2 f883 7500 40e2 01b7 3148 b0c0 0f01
c305

prints decimal representation of Fibonacci-numbers (truncated to last 64 bits) indefinitely

assembly code (fasm):

format ELF64 executable 3
segment readable writable executable

_start:
  inc rax
                  ; rbx is initialized to zero
.loop:
  push rax
  push rbx
  call print
  pop rax         ; old value for b
  pop rbx         ; old value for a
  add rax,rbx     ; (a,b) -> (b+a,a)
  jmp .loop       ; loop infinitely

print:
  mov rsi,buffer_end          ; point to end of buffer
  xor rbx,rbx
  mov bl,10                   ; store 10 in rbx
  mov [rsi],bl                ; append new-line
  mov dl,1                    ; length
.loop:
  mov dil,dl                  ; more counter to rdi
  xor rdx,rdx                 ; clear rdx
  div rbx                     ; divmod: quotient -> rax remainder -> rdx
  xchg dl,dil                 ; move remainder to rdi (and length to rdx)
  add dil,48
  dec rsi                     
  mov [rsi],dil               ; *buffer=n%10
  inc dl                      ; length++
  cmp rax,0
  jne .loop                   ; go back to loop if rax if not zero
  mov   dil,1                   ; stdout
  xor rax,rax
  mov   al,1                      ; sys_write
  syscall
  ret

print_buffer rb 128
buffer_end = $-1
\$\endgroup\$
2
\$\begingroup\$

Trilangle, 14 bytes

.'L1pj2'.S#1+|

Goes on forever in theory, but in practice it runs into the integer limit pretty quickly and spews garbage data.

You can try it on the online interpreter, but be ready to hit "stop program".

Unfolds to this:

    .
   ' L
  1 p j
 2 ' . S
# 1 + | .

Basically does this:

var x = 1, y = 1
while true {
    print(x)
    (x, y) = (y, x + y)
}
\$\endgroup\$
2
\$\begingroup\$

Labyrinth, 13 bytes

1
:!\
{ :
=+}

Try it online!

Infinitely prints fibonacci numbers separated by newlines.

1    Set up the stack to [(implicit 0) 1]

     Loop with stack content [x y]:
:!\  :!\   print y and a newline
{ :  :}    [x y | y]
=+}  +     [x+y | y]
     =     [y | x+y]
     {     [y x+y]
\$\endgroup\$
2
\$\begingroup\$

TypeScript’s type system, 97 bytes

//@ts-ignore
type F<N,L=[],A=[1],B=A>=L extends{length:N}?A["length"]:F<N,[...L,1],B,[...A,...B]>

Try it at the TS playground

This is a generic type F taking a number type N and outputting the Nth Fibonacci number, 0-indexed.

This solution won’t work past the first 20 Fibonacci numbers because of the max int (technically, max tuple size) limit.

Explanation: We start with the input number N, and L=[],A=[1],B=A. L keeps track of which Fibonacci number we’re on, and A and B are unary numbers (tuple-types of 1s) that track \$ f(n) \$ and \$ f(n + 1) \$ respectively.

First, check if L extends{length:N} (the length of L is N). If it is (?), return A["length"] (A as a decimal number).

Otherwise (:), recurse (F<…>), keeping N the same, increasing L’s length by 1 ([...L,1]), setting A to B, and setting B to A + B ([...A,...B]).

Alternatively, this can be done in 77 bytes with I/O in unary:

//@ts-ignore
type F<N,A=[1],B=A>=N extends[1,...infer N]?F<N,B,[...A,...B]>:A

Try it at the TS playground

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

Vyxal 3.5, 6 5 bytes

After nine two years in development, hopefully it will have been worth the wait.

11f⎄+

Vyxal It Online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 5 bytes: vyxal.github.io/… \$\endgroup\$ Commented Jan 13 at 0:01
  • \$\begingroup\$ Vyxal 3, 4 bytes: k±⎄+ Vyxal It Online! \$\endgroup\$ Commented Feb 25 at 9:44
2
\$\begingroup\$

Hatchback, 57 45 32 30 bytes

0 0 1 2 1 0 17 0 1 1 0 0 65281

since Hatchback has an integer limit of 0xFFFF, it stops at 9227465 and errors out.

it doesnt need 65535 at the end because it loops until error lol

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

Jalapeño, 11 bytes

1‽{₃⇥P1‥{₂⇥ₓ2Σ

Runs forever printing every fibbonacci number along the way. Very quickly succumbs to Double number precision error though.

Explained

1‽{₃⇥P1‥{₂⇥ₓ2Σ
1                 # Constant value 1 as the initial state for the while loop
 ‽                # state -> While condition(state) {state = body(state)}...
  {₄              # The condition consisting of the next 3 links
    ⇥P            # Print the last element of the list
       1          # Constant value 1, run forever
        ‥         # Concatenate to the end of the state...
         {₂       # The result of the next 2 links...
          ⇥ₓ2    # Tail 2, the last 2 elements of the list
              Σ   # Sum of

Hex-Dump of Bytecode

       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
0000: 31 a2 c7 dc 10 31 2e c6 df 32 e9                

Try it Online! WARNING Might crash your browser.

Or Just the First 100

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

TinyAPL, 14 bytes

{⊇+/∙×⍣⍵⍨⊤3‿2}

Thanks @noodle person for -1

Explanation

The solution is based on the matrix definition of Fibonacci numbers: \$\displaystyle \left[\matrix{1 & 1 \\ 1 & 0}\right]^n = \left[\matrix{F_{n + 2} & F_{n + 1} \\ F_{n + 1} & F_n }\right] \$

{⊇+/∙×⍣⍵⍨⊤3‿2}­⁡​‎‎⁡⁠⁢‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣​‎⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌­
 ⊇              ⍝ ‎⁡The bottom-right entry of
  +/∙×⍣⍵⍨       ⍝ ‎⁢the matrix power ⍵
         ⊤3‿2   ⍝ ‎⁣starting with [1‿1 ⋄ 1‿0]
💎

Created with the help of Luminespire.

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

TinyAPL, 12 bytes

{>⦅+/,>⦆⍣⍵1}

Output the first of repeatedly making the list (sum, first) N times, starting with 1.
(Taking the sum or the first item of just 1 gives 1.)

And yes, it is shorter to just port the classic APL solution using Pascal's triangle - that comes out to 10: ⦅0+/·!⟜⊖⍳⦆

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

SAKO, 60 bytes

1)CZYTAJ:N
B=.5
DRUKUJ(9,0):(B+B×5*B)*N/5*B
STOP1
KONIEC

Pretty basic solution printing N-th number using Binet's formula.

SAKO, 67 bytes

A=1
B=1
TEKST
1
1)DRUKUJ(9,0):B
B=B+A
A=B-A
SKOCZDO1
KONIEC

This one generates the Fibonacci sequence without end.

  1. Set A and B to 1, print it.
  2. Set A to B, and B to next Fibonacci number.
  3. Print B. Go to point 2.

Both solutions start printing in E notation for numbers longer than 10 digits, although at that point floating point inaccuracies probably already accumulated.

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

Python 3.8, 33 chars

lambda n:pow(p:=2<<n,n,p*p+~p)//p

Explanation

p*p+~p is equivalent to p*p - p - 1, the characteristic polynomial of the fibonacci sequence. This means that if we had the polynomial x*x - x - 1, then the nth fibonacci number is just the coefficient of x in x^n modulo (x*x - x - 1). However we are using a concrete integer p instead of a transcendent x element. The trick here is that p = 2**(n + 1) is large enough that the result does not "overflow" into the coefficients of the other polynomial coefficients. The last //p then just extracts the coefficient of x, since the result polynomial is at most of degree 1 (since we are getting the result modulo a degree-2 polynomial) and the constant coefficient is ignored.

\$\endgroup\$
1
4 5
6
7 8
12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.