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

334 Answers 334

1
5 6
7
8 9
12
1
\$\begingroup\$

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

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

\$\endgroup\$
2
  • \$\begingroup\$ Grar! Again? You beat me by one again. grumble \$\endgroup\$ Oct 30, 2015 at 20:26
  • \$\begingroup\$ .... ¯\_(ツ)_/¯ \$\endgroup\$ Oct 30, 2015 at 20:38
1
\$\begingroup\$

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

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

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)

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

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("~>"))))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why is the transpiled Python code not golfed D: \$\endgroup\$
    – Downgoat
    Feb 2, 2016 at 4:01
1
\$\begingroup\$

Oracle SQL 9.2, 80 bytes

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

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.

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

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.

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

CJam, noncompeting, 11 bytes

0X{_@+}q~*;
\$\endgroup\$
3
  • \$\begingroup\$ F(0) = 0. You should eliminate the backslash. \$\endgroup\$
    – Dennis
    Mar 2, 2016 at 15:40
  • \$\begingroup\$ Ah I was assuming that we were starting from 1,1..... so I guess this is a good convention since it saves a byte :) \$\endgroup\$
    – A Simmons
    Mar 2, 2016 at 16:18
  • \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Mar 2, 2016 at 16:29
1
\$\begingroup\$

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

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

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)

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

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.

\$\endgroup\$
3
  • \$\begingroup\$ Alpax doesn't exist anymore. \$\endgroup\$
    – user85052
    Dec 24, 2019 at 12:43
  • \$\begingroup\$ The Alpax repo is gone. Umm, is this language converted into Oasis? \$\endgroup\$
    – user92069
    May 11, 2020 at 8:32
  • \$\begingroup\$ @Λ̸̸ Alpax is/was a different language and a public repository is not available anymore. Oasis was another attempt at a golfing language specialized in sequences, which became a bit more successful and 'took over' the place of Alpax. \$\endgroup\$
    – Adnan
    May 11, 2020 at 16:17
1
\$\begingroup\$

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.

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

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();
    }
\$\endgroup\$
6
  • 2
    \$\begingroup\$ You don't have no support negative indices. Also, the "ternary" conditional operator isn't nasty if you use it right. :-) \$\endgroup\$ Apr 8, 2013 at 15:21
  • \$\begingroup\$ 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. \$\endgroup\$ Apr 8, 2013 at 15:28
  • 1
    \$\begingroup\$ lol - I posted mine without ever seeing yours. Funny to see that they're almost identical. :) \$\endgroup\$ Apr 17, 2013 at 17:54
  • 1
    \$\begingroup\$ Yeah, but trying to calculate anything above f(45) will cause either a StackOverflow, or just take forever and some time to calculate. \$\endgroup\$ Apr 17, 2013 at 18:09
  • 1
    \$\begingroup\$ I don't think you need the parentheses around (n<2) \$\endgroup\$
    – Cyoce
    May 2, 2016 at 15:00
1
\$\begingroup\$

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!

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

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!

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

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

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

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!

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

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

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can still golf it further. Try taking out the unnecessary whitespace. Also, there are some good tips here \$\endgroup\$
    – DJMcMayhem
    Sep 12, 2016 at 5:14
  • 2
    \$\begingroup\$ x=a+b;puts x can become puts x=a+b \$\endgroup\$
    – Cyoce
    Dec 11, 2016 at 3:26
1
\$\begingroup\$

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

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.

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

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.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ 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). \$\endgroup\$
    – user45941
    Nov 17, 2016 at 13:41
  • \$\begingroup\$ 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. \$\endgroup\$
    – Wheat Wizard
    Nov 17, 2016 at 13:56
  • \$\begingroup\$ The same can also be done with a=[1,1]. It can be shortened to a=1,1 \$\endgroup\$
    – Wheat Wizard
    Nov 17, 2016 at 14:00
1
\$\begingroup\$

Ruby (as function) 31 bytes

->n{a,b=1,0;n.times{a=b+b=a};b}
\$\endgroup\$
4
  • \$\begingroup\$ This is byte-per-byte exactly the same as another answer. \$\endgroup\$ Jan 18, 2017 at 0:28
  • \$\begingroup\$ 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. \$\endgroup\$
    – G B
    Jan 19, 2017 at 7:13
  • \$\begingroup\$ @VoteToClose Duplicate answers are allowed. \$\endgroup\$
    – DJMcMayhem
    Jan 19, 2017 at 7:17
  • \$\begingroup\$ 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. \$\endgroup\$
    – G B
    Jan 19, 2017 at 7:28
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\$

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

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".
\$\endgroup\$
1
5 6
7
8 9
12

Your Answer

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

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