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

238 Answers 238

4
\$\begingroup\$

bc, 36 chars

r=0;l=1;while(i++<99){r+=l;l+=r;r;l}
\$\endgroup\$
4
\$\begingroup\$

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

Mono Compilation

Visual Studio: 45

Func<int,int>f=null;f=n=>n>2?f(n-1)+f(n-2):1;
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Andrew Gray Apr 17 '13 at 18:14
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Troy Alford Apr 17 '13 at 18:45
  • 1
    \$\begingroup\$ 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: \$\endgroup\$ – Andrew Gray Apr 17 '13 at 18:49
  • \$\begingroup\$ Updated to clearly point out our findings. ;) \$\endgroup\$ – Troy Alford Apr 17 '13 at 18:53
  • \$\begingroup\$ 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 \$\endgroup\$ – Cyoce Mar 25 '16 at 5:59
4
\$\begingroup\$

Windows PowerShell – 34 30

for($b=1){$a,$b=$b,($a+$b)
$a}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Nov 19 '13 at 17:11
  • \$\begingroup\$ I can even save one more by including the initialisation in the loop header. \$\endgroup\$ – Joey Nov 19 '13 at 22:13
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Nov 27 '13 at 21:57
  • \$\begingroup\$ 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? \$\endgroup\$ – Iszi Nov 27 '13 at 22:06
  • \$\begingroup\$ @Iszi, give a separate answer, I guess. It solves a different problem, after all. \$\endgroup\$ – Joey Nov 28 '13 at 5:55
4
\$\begingroup\$

GNU Octave: 19 chars

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

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

\$\endgroup\$
  • \$\begingroup\$ Edited it to a language that I can test. \$\endgroup\$ – user2958652 Nov 18 '15 at 5:43
4
\$\begingroup\$

JavaScript, 41 39 33 bytes

(c=(a,b)=>alert(a)+c(b,a+b))(0,1)
\$\endgroup\$
  • \$\begingroup\$ I don't think the function without the parenthesis is still valid. \$\endgroup\$ – Denys Séguret Apr 8 '13 at 16:22
  • \$\begingroup\$ 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; \$\endgroup\$ – Kade Dec 16 '16 at 14:33
4
\$\begingroup\$

Cy, 33 31 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)
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

AsciiDots, 22 21 20 17 16 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!

\$\endgroup\$
4
\$\begingroup\$

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 _
\$\endgroup\$
  • 1
    \$\begingroup\$ This is possible in 31 bytes. See if you can see how :) \$\endgroup\$ – H.PWiz Dec 17 '18 at 7:33
4
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ 95? too lazy to check if algo is shorter \$\endgroup\$ – ASCII-only Jan 29 at 11:08
  • 1
    \$\begingroup\$ 94 and left sides in better order \$\endgroup\$ – ASCII-only Jan 30 at 6:29
  • \$\begingroup\$ @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). \$\endgroup\$ – ბიმო Jan 31 at 15:48
  • \$\begingroup\$ lol > bytes bytes \$\endgroup\$ – ASCII-only Jan 31 at 23:37
3
\$\begingroup\$

J - 20

First n terms:

(+/@(2&{.),])^:n i.2
\$\endgroup\$
3
\$\begingroup\$

Common Lisp, 48 Chars

(defun f(n)(if(< n 2) n(+(f(decf n))(f(1- n)))))
\$\endgroup\$
  • \$\begingroup\$ 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.) \$\endgroup\$ – Chris Jester-Young Apr 5 '11 at 2:12
  • \$\begingroup\$ 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 :-) \$\endgroup\$ – Dr. Pain Apr 29 '11 at 18:00
  • \$\begingroup\$ This is actually 47; you can get rid of the space between (< n 2) and n. \$\endgroup\$ – Joshua Taylor Nov 17 '15 at 20:54
  • \$\begingroup\$ And a slight modification is 46: (defun f(n)(if(< n 2)n(+(f(1- n))(f(- n 2))))). \$\endgroup\$ – Joshua Taylor Nov 17 '15 at 20:55
3
\$\begingroup\$

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$
\$\endgroup\$
  • \$\begingroup\$ Printing out overflowed numbers and/or segfaulting is probably not part of the spec, but nice try. :-) \$\endgroup\$ – Chris Jester-Young Apr 4 '13 at 11:53
  • \$\begingroup\$ 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. \$\endgroup\$ – Fors Apr 4 '13 at 13:09
  • \$\begingroup\$ Yay! Have an upvote. :-) \$\endgroup\$ – Chris Jester-Young Apr 4 '13 at 13:56
  • \$\begingroup\$ 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 :) \$\endgroup\$ – Matheus Avellar Aug 24 '17 at 16:29
3
\$\begingroup\$

BrainFuck, 172 characters

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

Credit goes to Daniel Cristofani

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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). \$\endgroup\$ – Joey Nov 28 '13 at 20:21
  • \$\begingroup\$ 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? \$\endgroup\$ – Iszi Nov 28 '13 at 22:57
  • \$\begingroup\$ I merely optimized it, since Remove-Variable takes a string[]. There is no need to have two calls ;-) \$\endgroup\$ – Joey Nov 29 '13 at 6:13
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Nov 29 '13 at 7:25
  • \$\begingroup\$ 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. \$\endgroup\$ – Joey Nov 29 '13 at 7:27
3
\$\begingroup\$

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 
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Michael Oct 14 '15 at 15:23
  • \$\begingroup\$ So it just runs so fast that all I can see is the zeros? \$\endgroup\$ – mbomb007 Oct 14 '15 at 18:39
  • \$\begingroup\$ 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. \$\endgroup\$ – Michael Oct 14 '15 at 19:37
  • \$\begingroup\$ 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. \$\endgroup\$ – mbomb007 Oct 14 '15 at 20:19
  • \$\begingroup\$ Yup, that seems to generate the same sequence as my version. \$\endgroup\$ – Michael Oct 14 '15 at 20:53
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Whoa. Just whoa. \$\endgroup\$ – Conor O'Brien Sep 24 '16 at 0:38
3
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ The loop for your "31 char" program would need to be included in the score. \$\endgroup\$ – mbomb007 Nov 4 '16 at 15:00
  • \$\begingroup\$ ^^ also, we usually give the count in bytes, not characters. \$\endgroup\$ – FlipTack Dec 28 '16 at 12:25
3
\$\begingroup\$

Javascript, 28 Characters

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

Try it here!

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! How about n<3? And do you really need the parentheses around the inequality? You can probably also omit the semicolon. \$\endgroup\$ – Martin Ender Mar 25 '17 at 19:43
3
\$\begingroup\$

Emojicode, 100 bytes

🐖🔢➡️🚂🍇🍊◀️🐕2🍇🍎🐕🍉🍓🍇🍎➕🔢➖🐕1🔢➖🐕2🍉🍉

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Common Lisp, 38 bytes

Generates the Fibonacci sequence without end.

(do((a 1 b)(b 1(+ a b)))(())(print a))

Try it online!

The other Common Lisp solution is a function to generate the n-th number. This solution works since in the do loop the assignments to the iteration variables are performed in parallel: so the initialization is equivalent to:

a, b = 1, 1

while at each repetition the assignment is equivalent to:

a, b = b, a+b
\$\endgroup\$
3
\$\begingroup\$

Lean, 42 35 bytes

7 bytes thanks to Mario Carneiro.

def f:_->nat|(n+2):=f(n+1)+f n|x:=x

Try it online!


Lean is a completely different kind of a programming language: it is a proof-assistant. That means, mathematical theorems can be formalized and proved in Lean, and mathematical objects can be constructed in Lean.

In this case, the auto-generated correctness theorems are (cf tio link):

f.equations._eqn_1 : f 0 = 0
f.equations._eqn_2 : f 1 = 1
f.equations._eqn_3 : ∀ (n : ℕ), f (n + 2) = f (nat.succ n) + f n
\$\endgroup\$
  • \$\begingroup\$ I had no idea anyone else knew about Lean. \$\endgroup\$ – qwr Mar 31 '18 at 17:38
  • \$\begingroup\$ "else" :o ... are you in the lean chat? \$\endgroup\$ – Leaky Nun Mar 31 '18 at 17:39
  • \$\begingroup\$ No, but the only reason I know it exists is because I know someone who contributed to it \$\endgroup\$ – qwr Mar 31 '18 at 17:47
  • \$\begingroup\$ @qwr might I know him? \$\endgroup\$ – Leaky Nun Mar 31 '18 at 17:47
  • \$\begingroup\$ If you know Jeremy Avigad \$\endgroup\$ – qwr Mar 31 '18 at 17:50
3
\$\begingroup\$

C++, 42 bytes

I haven't read every solution in this challenge, but the leaderboard doesn't have a C++ solution, which is a travesty.

int f(int i){return i-->1?f(i)+f(i-1):!i;}
\$\endgroup\$
3
\$\begingroup\$

bash pur, 49 chars, third solution

r=0;l=1;echo -e {1..45}" $((r+=l)) $((l+=r))\n";

bash pur, 52 chars, second solution

r=0;l=1;echo -e {1..40}" "$((r+=l))" "$((l+=r))\\n;

former solution (60 chars):

r=0;l=1;for i in {1..40};do((r+=l));((l+=r));echo $r $l;done
\$\endgroup\$
  • \$\begingroup\$ Could be written: r=1 l=0;echo -e {,,}{,,}{,,}" $[r+=l] $[l+=r]" \$\endgroup\$ – F. Hauri Feb 27 at 0:08
  • \$\begingroup\$ ... And former version: for((r=1,l=1;l<9**9;r+=l,l+=r)){ echo $r $l;} \$\endgroup\$ – F. Hauri Feb 27 at 0:16
  • 2
    \$\begingroup\$ 34 chars: for((a=1;b+=a;a+=b)){ echo $a $b;} \$\endgroup\$ – roblogic Aug 28 at 8:56
  • \$\begingroup\$ @F.Hauri: My improved solution is only 1 char longer than yours, with preserving the line oriented output, while your solution doesn't reach the max possible value before integer overrun. \$\endgroup\$ – user unknown Aug 28 at 19:27
  • 1
    \$\begingroup\$ @roblogic: In my opinion, negative results are not acceptable, but with a halting condition like for((a=1;b+=a;a+=b)){ echo $a $b;}|head -n46 your code is still 4 characters shorter than mine (improved one) - so why don't you publish your solution as an answer, or did you? \$\endgroup\$ – user unknown Aug 28 at 19:32
3
\$\begingroup\$

Flobnar, 19 bytes

@\
#_+_1
!_:.
9>$!,

Try it online!

Generates the sequence with no end, separating each number with a tab.


One year later...

I should probably check if I've already answered a question before I start coding...

Anyway, here's an alternative 19 byter that outputs in the same way, only 1-indexed this time and without the leading tab.

Flobnar, 19 bytes

!\$\@
:>+_,9
+ <>$.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ +1 for 'I should probably check if I've already answered a question' \$\endgroup\$ – EdgyNerd Aug 29 at 9:00
3
\$\begingroup\$

Java, 90 characters and just two variables

There was one before with 55 characters, but it used a variable without declaring it and had no output. This one has both and (the actual logic) is shorter. And as a little bonus it looks absolutely horrific code-style-wise and depends on compiler quirks, yay!

interface A{static void main(String[]x){for(int a,b=a=1;;System.out.println(b=a+(a=b)));}}

The special features I used are:

  • Using an interface instead of a class. The program can still be run as normal, but I don't need to write "public" twice. This saves 10 characters
  • Declaring multiple variables at once: int a,b;
  • Initializing multiple variables at once and in the declaration, needs a second a: b=a=1;
  • Everything is done in the for head, the body is empty: for(...);
    The first and third block of for are intended for variable initialization and variable incrementation, but they can hold any commands.
  • The whole logic is inside the output: System.out.println(b=a+(a=b))
  • Just two variables without recursion! This is done by using the way the compiler works: The assignment to b first reads the value of a, then it evaluates the right side of the +, where it reads the value of b and writes it into a, but the left side of the + still has the old value of a that gets added to the value of b after assigning the value of b to a. Then that sum gets written to b while a already holds the old value of b.
    I was lucky that the compiler works this way, because it could also have first evaluated the expression in the brackets, like for example C does, then it just lists all powers of 2 instead of the Fibonacci numbers.

In a dream programming language this would just be: b=a+(a=b

\$\endgroup\$
  • \$\begingroup\$ Dammit, referring to this answer just helped me in actually useful code, but I can't upvote it! :D \$\endgroup\$ – Fabian Röling May 27 at 21:56
2
\$\begingroup\$

Python, 36

f=lambda x:x>1and f(x-1)+f(x-2)or x
\$\endgroup\$
2
\$\begingroup\$

Python

a,b,n=0,1,10
while n:a,b,n=b,a+b,n-1;print b
\$\endgroup\$
  • 1
    \$\begingroup\$ a=b=1<newline>while 1:print a;a,b=b,a+b 30 Characters \$\endgroup\$ – st0le Feb 1 '11 at 6:19
  • \$\begingroup\$ @st0le that's actually 31 characters. I've spent like 5 minutes recounting my solution, which is identical to yours, until I came to the conclusion you are wrong :) \$\endgroup\$ – Mikle Nov 24 '11 at 18:02
  • \$\begingroup\$ The fibonacci sequence starts with 0. So you can't do a=b=1. It should be something like a,b=0,1\nwhile 1:print a;a,b=b,a+b which is 33 characters. \$\endgroup\$ – Bakuriu Sep 1 '12 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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