Fibonacci function or sequence

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.

/* 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 COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 3; // This should be the user ID of the challenge author.

/* App */

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

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

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

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

function process() {
var valid = [];

var body = a.body;
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],
});
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;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

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)
language = jQuery(language);
jQuery("#languages").append(language);
}

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

width: 290px;
float: left;
}

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

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• I am sort of waiting for a response like "f", 1 byte, in my math based golf language. Aug 11 '20 at 11:57

Fuzzy Octo Guacamole, 11 bytes

01(!aZrZo;)


This takes the infinite route.

Explanation:

01 pushes 0 and then 1 to the stack.

( starts a infinite loop.

! sets the register, saving the value on the top of the stack and storing it. It doesn't pop though.

a adds the 2 values.

ZrZ reverses the stack, pushes the register contents, and reverses again. This pushes the stored number to the bottom of the stack.

o; peeks and prints.

) ends the infinite loop.

Then the whole things starts again from the (.

As a a side note, this is quite fast to hit the max long size possible in Python. The last number it prints is 12200160415121876738, and it repeats that forever.

Python 2, 43 bytes

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


Perl 5, 23 bytes

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

say$.-=$b+=$.*=-1;redo  Hat tip. Python 33 characters x,y=0,1 while 1:print x;x,y=y,x+y  This will be an infinite loop! Python 31 characters def f(a=[1,0]):a[:]=a[1],sum(a)  demonstration for _ in range(10): f(); print f.func_defaults[0][0] 0 1 1 2 3 5 8 13 21 34  • The loop for your "31 char" program would need to be included in the score. Nov 4 '16 at 15:00 • ^^ also, we usually give the count in bytes, not characters. Dec 28 '16 at 12:25 Cylon (Non-Competing), 12 bytes The language is in development, Im just putting this up here. 1:øÌ[:ì+Á])r  An explanation: 1 ;pushes a 1 to the stack : ;duplicates the top of the stack ø ;reads a number from stdin, pushing it to the stack Ì ;non-pushing loop, doesn't push counter to the stack, but deletes it [ ;start of function, to be pushed to the stack : ;duplicate top of stack ì ;rotate the stack, moving the copy to the back + ;replaces top two objects on the stack with their sum Á ;push the result to the shadowing stack (non-consuming) ] ;end of function ) ;switch to shadowed stack r ;standard library call, reverses a stack ;stack implicitly printed  bc, 21 for(b=1;b=a+(a=b);)a  The trailing newline is significant. Outputs the entire sequence. bc has arbitrary precision arithmetic, so this continues forever. OIL, 46 bytes This program writes an infinite unstoppable stream of fibonacci numbers. It is mostly copied from the standard library but fit to the requirements and golfed. 14 add 17 17 14 swap 17 17 4 17 11 6 0 0 1  • Welcome to the site! This is a cool answer, I've never heard of the language before. :) May 4 '17 at 17:29 Python 2, 30 bytes f=lambda n:n<3or f(n-2)+f(n-1)  Try it online! One catch: this outputs True instead of 1. This is allowed by this meta consensus. Gaia, 6 bytes 0₁@+₌ₓ  I might make a built-in for this in the future, but built-ins are boring anyway. Explanation 0₁ Push 0 and 1 @ Push an input +₌ₓ Add the top two stack elements, without popping them, (input) times Implicitly print the top stack element.  Husk, 7 2 bytes (non-competing) İf  Try it online! Python 2, 49 40 chars a,b=0,1 exec"a,b=b,b+a;"*input() print b  Function form, 44 chars def f(n):a,b=0,1;exec"a,b=b,b+a;"*n;return b  My take on this challenge. Didn't find this kind of an answer yet. I hope it's a valid one. Print's n:th Fibonacci number. Functions by multiplying the string inside exec n times and then executing it as Python. Edit: input() instead of int(raw_input()) • If I'm not mistaken, you don't need to the () around exec in Python 2. Jul 21 '17 at 14:07 • @StepHen That seems to be true, thanks, down by 2 chars – SydB Jul 21 '17 at 14:11 • Oh, I almost forgot: this would be considered a snippet because it preassumes the value of n. Generally you must write either a full program that gets input, or a function. So, you would have to replace n with input(). See this meta post for more information. Jul 21 '17 at 14:15 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, ' ';
}

• This can be 31 bytes since you don't need PHP's opening tag (you can run with php -r "code here" without opening tag) and you can use _ as separator instead of space: Try it online! Sep 25 '19 at 9:42

Klein, 2322 21 + 3 = 24 bytes (non-competing)

Run with the 000 topology

(1)\((@
):?\1-+(:(+)$ Explanation When the program starts it executes (1) which will put a 1 under the input. It then deflects into the main loop. The main loop is on the second line. It starts with the \ character. Unwrapped it looks like: \1-+(:(+)$):?


This will redirect our pointer if the counter is zero or perform one iteration of the fibonacci sequence otherwise.

Once the counter reaches zero we are deflected to the code ((@, this will hide the top two values (the counter and one of the fibonacci numbers) and terminate the program.

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]

C, 64 bytes

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


Try it online! Uses the same method as my Implicit answer.

• Aug 19 '18 at 4:01

Pyt, 1 byte

Get the nth Fibonacci number:

Ḟ


Explanation:

           Implicit input
Ḟ         Return (input)-th Fibonacci number


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!

><>, 11 bytes

10r:n:@+aor


Try it online!

Prints the Fibonacci sequence forever, separated by newlines.

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

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


Try it online!

• You should add a TIO link and some sample cases Aug 9 '18 at 19:32
• @MuhammadSalman They do not have to add a link. I think "should" is a bit too forceful. Aug 9 '18 at 19:52
• Ok I added the TIO link, this is my first time posting Aug 9 '18 at 22:04
• @mrFoobles For demonstration purposes, I think main=print f would be more impressive as it shows the magnitude of infinite lists. Aug 9 '18 at 22:19
• @JonathanFrech yeah, should have been you could add and not should add Aug 10 '18 at 10:28

Prolog, 3635 29 bytes

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


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

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

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

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

• Welcome to PPCG! The usual consensus is to include the function invocation if it needs to be called with special arguments. Nov 4 '18 at 10:46
• Should I include the call in the character count? Nov 4 '18 at 16:54
• 26 bytes: X+Y+O:-O=X;Z is X+Y,Y+Z+O. Try it online! Feb 5 '20 at 19:18

Burlesque, 8 bytes

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

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

{0 1q?+#RC!}RS


Explanation

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

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

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


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

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


Older Stuff

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

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


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

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


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

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


• This is code-golf, so please post the shortest solution you can find with its byte count. Oct 22 '15 at 17:20

Alchemist, 68 bytes

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


Try it online!

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

Explanation:

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

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

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

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


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

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


BitCycle, 21 bytes

  1+ ~!
CB0CA~
^ 1  <


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

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

Explanation

This explanation assumes you're familiar with BitCycle.

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

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

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

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

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

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

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

Other versions

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

10>v ~!
BA+BA~
^    <


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

 1+ ~!
CBCA~
^10 <


Pyramid Scheme, 385 bytes

   ^           ^
/ \         /l\
/set\       /oop\
^-----^     ^-----^
-    ^-    /]\   ^-^
^-    ^---^ ^- -^
^-    ^-   -/ \  -^
^-     -^   /set\  -^
/[\     / \ ^-----^  -^
^---^   /out\-    ^-  / \
-^  -^ ^-----^   /+\ /set\
/1\ / \-    /x\ ^---^-----^
---/set\    --- -  /x\   /+\
^-----^          ---  ^---^
/x\   /1\             /x\  -
---   ---             ---


Try it online!

This guy's a whopper. Prints terms indefinitely with no separator. The bit on the left initializes the blank variable and x to one, and the bit on the right does the Fibonaccing. The loop condition (everything to the left below loop) prints both variables before checking the blank one for truthiness (it'll always be nonzero). The loop body updates first blank and then x, thus generating the next two terms for the condition to print.

I can't quite figure out set. It doesn't quite follow the chain of execution, but it almost does, I think. I'll be looking at the Pyramid Scheme source in the next few days (and possibly extending the language); perhaps this will provide me with the insight required to golf some bytes off this monstrosity.

BitCycle, 17 16 bytes

~1~ +
AB~/!
^ +/


Try it online!

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

~1~+
AB~!
^ +/


Try it online!

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

There's also a 17 byte solution:

v0<
AB~
~ +\
~  !


Try it online!

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

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

Explanation:

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

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

~ ~    Invert the whole stack
AB~    This basically swaps the values of the two numbers
Also duplicate a copy downwards and rightwards

       Split the stream into zeroes and ones with the plus
!  /!  Print a single 0 as the separator
^ +/   And add a copy of the 1s to the collector

  ~ +
!  Print a copy of the 1s to the output


This repeats infinitely, basically executing the pseudocode:

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


pure bash, 43 chars

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


Not really golfed, but I like it anyway.

Or

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


Zsh, 31 bytes

try it online

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


32 bytes, based on James Brown's awk solution:
for ((y=1;z=x+y;y=z))echo $[x=y] 42 bytes, to halt before int overflow: (for ((a=1;b+=a;a+=b))echo$a \$b)|head -46

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

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


Try it online!

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

Unfolded, this looks something like:

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


Try it online!

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

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


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

Taktentus, 87 bytes

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


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

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)