# 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, 2020 at 11:57
• @ChrisJesterYoung can we use 1.0 are 1 only? May 11 at 2:45
• @NumberBasher 1.0 is fine. May 20 at 19:10

# R, 40 bytes

Haven't seen a R solution, so:

f=function(n)ifelse(n<3,1,f(n-1)+f(n-2))

• I know this is an old answer, but you can shorten to 38 bytes Aug 3, 2018 at 14:53

# Whispers v3, 35 bytes

> Input
> fₙ
>> 2ᶠ1
>> Output 3


Try it online! (or don't, as this uses features exclusive to v3)

Simply takes the first $$\n\$$ elements of the infinite list of Fibonacci numbers.

• Welcome to Code Gol...hey wait a minute Feb 19, 2021 at 19:00

## GolfScript, 13 chars

2,~{..p@+.}do


(My answer from a previous Stack Overflow question.)

# JavaScript, 4139 33 bytes

(c=(a,b)=>alert(a)+c(b,a+b))(0,1)

• I don't think the function without the parenthesis is still valid. Apr 8, 2013 at 16:22
• I don't believe this is valid because ES6 came after the challenge was created. Even if it was, you could save a byte by making it a function to return fib(n): f=(n,a=0,b=1)=>n?f(n-1,b,a+b):a;
Dec 16, 2016 at 14:33

# jq-n, 30 28 bytes

-2 bytes thanks to Michael Chatiskatzi!

Prints the infinite sequence.

[0,1]|while(1;[last,add])[1]


Try it online!

Start with [0,1].
while(1; ... ) infinite loop, 1 is a truthy value.
[last,add] the new pair is the last value of the old pair and the sum of the old pair.
while returns all intermediate pairs, [1] gets the second element of each pair.

# jq, 35 33 bytes

A recursive filter written for this tip.

def f:(.<2//[.-1,.-2|f]|add?)//.;


Try it online!

• 28 bytes Sep 10, 2021 at 21:45

# bc, 36 chars

r=0;l=1;while(i++<99){r+=l;l+=r;r;l}


# C: 48 47 characters

A really really truly ugly thing. It recursively calls main, and spits out warnings in any sane compiler. But since it compiles under both Clang and GCC, without any odd arguments, I call it a success.

b;main(a){printf("%u ",b+=a);if(b>0)main(b-a);}


It prints numbers from the Fibonacci sequence until the integers overflow, and then it continues spitting out ugly negative and positve numbers until it segfaults. Everything happens in well under a second.

Now it actually behaves quite well. It prints numbers from the Fibonacci sequence and stops when the integers overflow, but since it prints them as unsigned you never see the overflow:

VIC-20:~ Fors$./fib 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 VIC-20:~ Fors$

• Printing out overflowed numbers and/or segfaulting is probably not part of the spec, but nice try. :-) Apr 4, 2013 at 11:53
• Certainly, but it's not the only solution here that segfaults. :) I will edit it so that it behaves more properly, since I got the character count down anyway.
– Fors
Apr 4, 2013 at 13:09
• Yay! Have an upvote. :-) Apr 4, 2013 at 13:56
• I'm pretty sure you could shave off 2 bytes by replacing if(b>0) with b>0&& and yes, I realize this post is over 4 years old :) Aug 24, 2017 at 16:29

# C#: 38 (40 to ensure non-negative numbers)

Inspired by the beauty of Jon Skeet's C# answer and St0le's answer, another C# solution in only 38 characters:

Func<int,int>f=n=>n>2?f(n-1)+f(n-2):1;


Tested with:

for(int i = 1; i <= 15; i++)
Console.WriteLine(f(i));


Yay for recursive Func<>! Incorrect when you pass in negative numbers, however - corrected by the 40 character version, which doesn't accept them:

Func<uint,uint>f=n=>n>2?f(n-1)+f(n-2):1;


Note: as pointed out by @Andrew Gray, this solution doesn't work in Visual Studio, as the compiler rejects the in-line function definition referring to itself. The Mono compiler at http://www.compileonline.com/compile_csharp_online.php, however, runs it just fine. :)

Visual Studio: 45

Func<int,int>f=null;f=n=>n>2?f(n-1)+f(n-2):1;

• looks rather familiar...dunno where I've seen that before... ;) As far as I can tell, though, in C# this is the best way of doing it. However, your way won't work - you have to assign null to your function to use a recursive lambda. As that code stands, it won't compile, with a syntax error 'use of unassigned function f' at the line that your lambda is being defined at. Apr 17, 2013 at 18:14
• Depends on your compiler. :) It does exactly as you say in Visual Studio - but the Mono compiler at compileonline.com/compile_csharp_online.php runs it perfectly as-is. Apr 17, 2013 at 18:45
• Didn't know that. I wonder why VS and Mono went two different directions on this one...or, maybe the Mono guys are just smarter. The answer is beyond me. D: Apr 17, 2013 at 18:49
• Updated to clearly point out our findings. ;) Apr 17, 2013 at 18:53
• Does this handle the F(0)=0 case? It's an easy fix that doesn't cost any extra bytes: just exchange :1 for :n Mar 25, 2016 at 5:59

### Windows PowerShell – 34 30

for($b=1){$a,$b=$b,($a+$b)
$a}  • You can save 3 by doing away with defining$a at the start (assuming $a is not already defined in the environment), and moving the echo of$a to the end of the loop.
– Iszi
Nov 19, 2013 at 17:11
• I can even save one more by including the initialisation in the loop header.
– Joey
Nov 19, 2013 at 22:13
• Wow. I never actually ran this until today for some reason. It's interesting that, past around 1E+308, PowerShell just gives up and calls it Infinity.
– Iszi
Nov 27, 2013 at 21:57
• I put together a solution, somewhat based on this, that accepts user input and outputs the nth number. Came out to 45 characters. You want that here, or as a separate answer?
– Iszi
Nov 27, 2013 at 22:06
• @Iszi, give a separate answer, I guess. It solves a different problem, after all.
– Joey
Nov 28, 2013 at 5:55

GNU Octave: 19 chars

@(x)([1,1;1,0]^x)(1)


This solution has the distinction of running in O(log n) time.

• Edited it to a language that I can test. Nov 18, 2015 at 5:43

# Cy, 3331 30 bytes (non-competing)

This is going for the function option (takes N, outputs F(N))

0 1 :>i {1 - $&+ times} &if :<  Ungolfed/explanation: 0 1 # first two fibs are 0, 1 :>i # read input as integer (let's call it N) { 1 - {&+} # add the last two values times # repeat N-1 times ^ } &if # if N is non-zero ^ :< # output the last calculated value (if N is 0, that would be 0)  # Detour (non-competing), 8 bytes [$<<]!S.


Try it online!

This one is shorter than the word "fibonacci"

[$<<]!S. Fibonacci  explanation: [ ] # while n > 0$<<       # replace n with [n-1, n-2]
!S.  # invert, output


Just for fun, here's one that will always take exactly 19 ticks to terminate, whether given 0 or 1474. On my really old macbook, it on average terminates after 7ms.

# Detour, 30 28 bytes

$Q{G<!d}seQ .{5Vg>d}se-$G_c!


Try it online! This is the way of expressing (((1+sqrt(5))/2)^n-((1-sqrt(5))/2)^n)/sqrt(5)

Old way:

# Detour (non-competing), 10 9 bytes

<Q>S.
;$<  Try it online! This is non-competing: I just pushed the required version of the language about 10 minutes ago. Detour works like befunge, fish etc. except for one crucial difference: where those languages redirect the instruction pointer, detour redirects data. Input is pushed in at the beginning of the middle line (in this case the first). < decrements a number, > increments it. Q sends it down if a number is greater than 0, forward otherwise. the line ;$< is the same as $<; because edges wrap. What it does is take the number it is given, then push that number and 1 less than that number to the input. This is how detour does recursion. S reduces with addition, and . outputs the result. For a better explanation, visit the site and it will give a visual representation of all the numbers. # AsciiDots, 2221201716 15 bytes /.{+}-\ \#$*#1)


Prints the Fibonacci sequence. Outgolfs the sample by 12 13 14 17 18 19 bytes. This is now just 1 byte longer than exactly as long as a simple counter! Try it online!

# AsciiDots, 31 30 bytes

 /#$\ .>*[+] /{+}* ^-#$)
\1#-.


Here's a faster version. It prints out the Fibonacci sequence at a rate of 1 number per 5 ticks, compared to the maximally golfed version's 1 per 8 10 8 12 14 ticks. It's twice as fast as the sample and is still shorter by 3 4 bytes! Try it online!

# Symbolic Python, 34 31 bytes

-3 bytes thanks to H.PWiz!

__('__=_/_;'+'_,_=_+__,__;_'*_)


Try it online!

Returns the nth element of the Fibonacci, 1-indexed, starting from 1,1,2,3,5....

### Explanation:

__(                           ) # Eval as Python code
'__=_/_;'                    # Set __ to 1
+'             '*_  # Then repeat input times
_,_=_+__,__;      # On the first iteration, set _ to __ (1)
;_     # On future iterations, prepend a _
__,_=_+__,__;      # Set __ to the next fibonacci number
# And set _ to the old value of __
# Implicitly output _


Or, H.PWiz's version:

__('_=__=_/'+'_;__,_=_+__,_'*_)


Try it online!

### Explanation:

__('_=__=_/'+'_;__,_=_+__,_'*_)

__(                           ) # Eval as Python code
'_=__=_/'+'_;                # Set both _ and __ to 1
'             '*_  # Repeat input times
__,_=_+__,__    # Set __ to the next fibonacci number
# And set _ to the old value of __
__,_=_+__,_     # Except on the last iteration
# Implicitly output _

• This is possible in 31 bytes. See if you can see how :) Dec 17, 2018 at 7:33

# Alchemist, 104 87 bytes

-10 bytes thanks to ASCII-only!

_->b+c+m
m+b->m+a+d
m+0b->n
n+c->n+b+d
n+0c->Out_a+Out_" "+o
o+d->o+c
o+0d+a->o
o+0a->m


Produces infinitely many Fibonacci numbers, try it online!

## Ungolfed

_ -> b + c + s0

# a,d <- b
s0 +  b -> s0 + a + d
s0 + 0b -> s1

# b,d <- c
s1 +  c -> s1 + b + d
s1 + 0c -> Out_a + Out_" " + s2

# c <- d & clear a
s2 +  d     -> s2 + c
s2 + 0d+  a -> s2
s2     + 0a -> s0


Try it online!

• 95? too lazy to check if algo is shorter Jan 29, 2019 at 11:08
• 94 and left sides in better order Jan 30, 2019 at 6:29
• @ASCII-only: Nice! Noticed I can also output $\infty$ many terms, saved another 7 bytes.. but Alchemist indeed needs some work done (atm. it only works when properly killing the process due to some buffering issues). Jan 31, 2019 at 15:48
• lol > bytes bytes Jan 31, 2019 at 23:37

# Intel 8087 FPU, 13 bytes

Binary:

00000000: d9e8 d9ee dcc1 d9c9 e2fa df35 c3         ...........5.


Listing:

D9 E8       FLD1                ; push initial 1 into ST(1)
D9 EE       FLDZ                ; push initial 0 into ST
FIB_LOOP:
DC C1       FADD ST(1), ST      ; ST(1) = ST(1) + ST
D9 C9       FXCH                ; Exchange ST and ST(1)
E2 FA       LOOP FIB_LOOP       ; loop until n = 0
DF 35       FBSTP [DI]          ; store result as BCD to [DI]


As a callable function, input n in CX, output to a 10 byte little-endian packed BCD representation at [DI]. This will compute up to Fibonacci n=87 using the Intel x87 math-coprocessor using 80-bit extended-precision floating point arithmetic.

Run using DOS DEBUG with n = 9, result 34:

n = 87 (0x57), result 679891637638612258:

# convey, 8 bytes

Generates the sequence.

v+"}
1"1


Try it online!

The values (initially 1 and 1) follow the conveyor belts indicated by the arrow heads. " duplicates the input into both outputs, + adds them, and } writes them to the output.

# COBOL (GNU), 170 bytes

I am surprised at the lack of COBOL answers on this site. Well, it is ancient after all.

This outputs the fibonacci sequence correctly up to 38 digits.

PROGRAM-ID.H.DATA DIVISION.LOCAL-STORAGE SECTION.
1 a PIC 9(38).
1 b PIC 9(38).
PROCEDURE DIVISION.G.COMPUTE a=0**b+b -a
DISPLAY b(38- FUNCTION LOG10(b):)GO G.


Try it online!

## Explanation

We just need two variables, a and b to compute the whole fibonacci sequence. Here is pseudocode of what this would look like:

a = 0
b = 1
loop {
a = b - a
b += a
print(a)
}


Translating the pseudocode above in COBOL is relatively short and simple. But we see that variables in COBOL are set to 0 by default, and having one of them set to a 1 is kind of (8 bytes) long, so we hack it out like so:

a = 0
b = 0
loop {
a = b - a + 0 ** b
b += a
print(b)
}


The 0 ** b ensures that a = 1 on the first iteration. From then on, the logic is the same as in our first pseudocode implementation (since 0 ** (any number greater than 0) = 0). The change from print(a) to print(b) is just to ensure that the numbers are outputted in the correct order.

### Ungolfed

PROGRAM-ID. H.

DATA DIVISION.
LOCAL-STORAGE SECTION.
1 a PIC 9(38).                     // Declare a variable named a (a = 0)
1 b PIC 9(38).                     // Declare a variable named b (b = 0)

PROCEDURE DIVISION.
G.                                 // Define a label named G
COMPUTE a=0**b+b -a                // a = b - a + 0 ** b
ADD a TO b                         // b += a
DISPLAY b(38- FUNCTION LOG10(b):)  // Print b without trailing zeros
GO G.                              // Jump to the label named G (4 lines above)


# Vyxal, 2 bytes

ÞF


Try it Online!

Before you go saying that the online link doesn't match the submission here, that's because the extra , is needed to actually make the output appear online. If you use the offline version, then you will see that the above works just fine. Also, the 5 flag makes sure that the online interpreter times out after 5 seconds.

## Explained

ÞF  # Push every Fibonacci number


And now for the non-trivial version

## Vyxal5, 6 bytes

⁽+dk≈Ḟ


Try it Online!

Once again, discrepancies between online link and actual version are for the purposes of making it work online.

### Explained

⁽+dk≈Ḟ
⁽+d     # lambda x, y: x + y
k≈   # the list [0, 1]
Ḟ  # Create an infinite sequence based on the function and the initial list.


Fun fact: the infinite sequence function you see was inspired by the sequence blocks of the golfing language Arn by ZippyMagician.

• Fun fact: I was inspired by Raku when I added sequences Apr 11, 2021 at 2:36

# Quipu, 33 bytes

1&0&\n
[][]/\
^^/\0&
--++??
1&
++

Attempt This Online!

Saved 4 bytes thanks to Jo King.

It prints the Fibonacci sequence separated by newlines.

Equivalent pseudocode:

  a = [0, 0, 0]    // implicitly
0:
a[0] = a[1] - a[0] + 1
1:
print a[0]
a[1] = a[0] + a[1]
2:
print "\n"
goto 0

• Kaogu. (15chrs)
– null
Apr 15 at 14:39

# Fig, commit df1d8a1, $$\5\log_{256}(97)\approx\$$ 4.125 bytes

G:1'+


New language! Yay! This is a fractional byte language I've been advertising on TNB for a while now. It's pure printable ASCII, and has a 97 char codepage. Although the spec is mostly written by now, this commit only has the bare minimum implemented for this challenge. To run this, download the source and then run in the root directory:

./gradlew run --args="code.txt"


It will print Fibonacci numbers until your computer runs out of RAM. Explanation:

G:1'+ - Takes no input
G     - Generate an infinite list using initial terms...
:1   - [1, 1]...
'  - And the generating function...


# Trianguish, 152 135 bytes

00000000: 0c05 10d8 0201 40d7 0401 4110 4102 a060
00000010: 2c02 b080 2c02 8050 20e4 0211 0710 e209
00000020: 1110 4028 0d00 6020 2902 10c3 0802 a107
00000030: 02a1 0502 8027 0910 290b 1110 403b 0890
00000040: 204d 03d0 503c 0790 602a 1071 02a0 9027
00000050: 0280 b110 8111 0402 70e2 0501 402a 0202
00000060: 9106 1107 0291 0b11 0902 702b 1040 2a10
00000070: 6110 2102 9050 2802 70b1 1071 1104 1102
00000080: 02a1 0502 802c 05


Try it online!

Trianguish is my newest language, a cellular automaton sort of thing which uses a triangular grid of "ops" (short for "operators"). It features self-modification, a default max int size of 216, and an interpreter which, in my opinion, is the coolest thing I've ever created (taking over forty hours and 2k SLOC so far).

This program consists of two precisely timed loops, each taking exactly 17 11 ticks. The first, in the top right is what actually does the fibonacci part; two S-builders are placed in exactly the right position such that two things occur in exactly the same number of ticks:

1. The left S-builder, x, copies its contents to y
2. The sum of x and y is copied to x

Precise timing is required, as if either of these occurred with an offset from the other, non-fibonacci numbers would appear in brief pulses, just long enough to desync everything. Another way this could have been done is with T-switches allowing only a single tick pulse from one of the S-builders, which would make precise timing unneeded, but this is more elegant and likely smaller.

The second loop, which is also 11 ticks, is pretty simple. It starts off with a 1-tick pulse of 1n, and otherwise is 0n, allowing an n-switch and t-switch to allow the contents of x to be outputted once per cycle. Two S-switches are required to make the clock use an odd number of ticks, but otherwise it's just a loop of the correct number of wires.

This program prints infinitely many fibonacci numbers, though if run with Mod 216 on, it will print them, as you might guess, modulo'd by 216 (so don't do that :p).

### J - 20

First n terms:

(+/@(2&{.),])^:n i.2


# Common Lisp, 48 Chars

(defun f(n)(if(< n 2) n(+(f(decf n))(f(1- n)))))

• Is left-to-right evaluation order guaranteed in CL? If not, your solution won't work. (There is no such guarantee in Scheme, and many implementations are right-to-left.) Apr 5, 2011 at 2:12
• Left-to-right is in the standard so since these are all built-in functions it is reliable. (Macros can of course do stupid things :-) Apr 29, 2011 at 18:00
• This is actually 47; you can get rid of the space between (< n 2) and n. Nov 17, 2015 at 20:54
• And a slight modification is 46: (defun f(n)(if(< n 2)n(+(f(1- n))(f(- n 2))))). Nov 17, 2015 at 20:55

## BrainFuck, 172 characters

>++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]


Credit goes to Daniel Cristofani

# PowerShell: 42 or 75

Find nth Fibonacci number - 42

A spin-off of Joey's answer, this will take user input and output the nth Fibonacci number. This retains some weaknesses also inherent to Joey's original code:

• Technically off by 1, since it starts the Fibonacci sequence at 1,1 instead of the more proper 0,1.
• Only valid for Fibonacci numbers which will fit into int32, because this is PowerShell's default type for integers.
• Example: Due to the int32 limitation, the highest input that will return a valid report is 46 (1,836,311,903) and this is technically the 47th Fibonacci number since zero was skipped.

Golfed:

($b=1)..(read-host)|%{$a,$b=$b,($a+$b)};$a  Un-Golfed & Commented: # Feed integers, from 1 to a user-input number, into a ForEach-Object loop. # Initialize$b while we're at it.
($b=1)..(read-host)|%{ # Using multiple variable assignment... # ...current$b is put into new $a, and... # ...sum of current$b and current $a are put into new$b.
$a,$b=$b,($a+$b) }; # When loop exits, output$a.
$a # Variable cleanup, not included in golfed code. rv a,b  List Fibonacci numbers - 75 Another derivative of Joey's answer, but with some improvements: • Zero is included in the output, as it should be according to OEIS. • Goes up to the maximum Fibonacci number that can be handled as uint64 instead of the default int32. (Highest Fibonacci number in uint64 is 12,200,160,415,121,876,738.) • Output stops once the maximum value is reached, instead of looping through 'Infinity' or continuously throwing errors. Golfed: for($a,$b=0,1;$a+$b-le[uint64]::MaxValue){$a;$a,$b=$b,[uint64]($a+$b)}$a;$b  Un-Golfed & Commented: # Start Fibonacci loop. for ( # Begin with$a and $b at zero and one.$a,$b=0,1; # Continue so long as the sum fits in uint64.$a+$b-le[uint64]::MaxValue ) { # Output current$a.
$a; # Using multiple variable assignment... # ...current$b becomes new $a, and... # ...sum of current$b and current $a is forced to uint64 and stored in new$b.
$a,$b=$b,[uint64]($a+$b) } # Output$a and $b one more time.$a;$b # Variable cleanup - not included in golfed code. rv a,b  • One thing that bugs me a little in PowerShell: Read-Host always reads interactively and won't pick up things you pipe into the script (or process), whereas $input (which is what I tend to use) only picks up piped input (for obvious reasons; that's how it's defined) but cannot be used interactively. Which means that you can write a PowerShell script that either works interactively or one that works with piped input, but not both at the same time (at least not for golfing).
– Joey
Nov 28, 2013 at 20:21
• Yeah, and I personally prefer my scripts to be interactive whether the challenge calls for it or not. Wait... Did you just golf the un-golfed code? And not just any part of it, but particularly the bit that's not at all in the golfed code?
– Iszi
Nov 28, 2013 at 22:57
• I merely optimized it, since Remove-Variable takes a string[]. There is no need to have two calls ;-)
– Joey
Nov 29, 2013 at 6:13
• I meant to say I found it amusing that of all the code to be optimized, you had to go and fix the bit that wasn't even part of the golfed solution. It's like you had an OCD moment or something.
– Iszi
Nov 29, 2013 at 7:25
• Sometimes I do ;-). I don't see anything that makes the golfed code smaller either. For an algorithm this simple there aren't many options and range|% is often the shortest (but also the slowest) way.
– Joey
Nov 29, 2013 at 7:27

## Forth - 38 33 bytes

: f dup . 2dup + 2 pick recurse ;


Generates and prints a Fibonacci series recursively until it runs out of stack space.

Usage:

 1 1 f


Or to generate Fn, where n>=1 (66 bytes):

: f dup 3 < if 1 nip else dup 1- recurse swap 2 - recurse + then ;


Example of usage:

9 f .


output:

34

• It does work, but like I said it doesn't terminate itself. It should generate correct output up until 46! at least, and after that it will just keep on going and output "garbage". And since that online compiler doesn't appear to have any way of halting the execution without clearing the console output it gets pretty hard to see the correct output at the beginning. Oct 14, 2015 at 15:23
• So it just runs so fast that all I can see is the zeros? Oct 14, 2015 at 18:39
• Right. If you run it in Win32Forth you can scroll up and get it to stay at the top so that you actually can see the correct output for Fn up to n=46. Oct 14, 2015 at 19:37
• Also, if I'm not mistaken : f over . 2dup + recurse ; is shorter (27 bytes). This way, the first number is printed first, and the numbers are in order on the stack, so we don't need 2 pick. Oct 14, 2015 at 20:19
• Yup, that seems to generate the same sequence as my version. Oct 14, 2015 at 20:53

# Java, 41 bytes

There are a couple other Java answers here, but I'm surprised nobody has posted this simple one:

int f(int n){return n<2?n:f(n-1)+f(n-2);}


For an extra byte you can extend the range up to long.

# TeaScript, 4 bytes

F(x)

F(x) //Find the Fibonacci number at the input


Compile online here (DOES NOT WORK IN CHROME). Enter input in the first input field.

• This entry fails the creating a compiler after a challenge has been posted loophole and therefore isn't valid. I can't accept this answer, sorry. Nov 3, 2015 at 19:14
• With TeaScript 3, you can just do Fß. Jan 29, 2016 at 6:03

# J, 9 bytes

+/@:!&i.-


Gets the nth Fibonacci number by finding the sums of the binomial coefficients C(n-i-1, i) for i from 0 to n-1.

Also, a short way using 12 bytes to generate the first n Fibonacci numbers is

+/@(!|.)\@i.


It uses the same method as above but works by operating on prefixes of the range [0, 1, ..., n-1].

### Usage

   f =: +/@:!&i.-
f 10
55
f 17
1597


### Explanation

+/@:!&i.- Input: n
- Negate n
&i.  Form the ranges [n-1, n-2, ..., 0] and [0, 1, ..., n-1]
!     Find the binomial coefficient between each pair of values
+/@:      Sum those binomial coefficients and return

• Whoa. Just whoa. Sep 24, 2016 at 0:38