129
\$\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\$
1
  • 2
    \$\begingroup\$ I am sort of waiting for a response like "f", 1 byte, in my math based golf language. \$\endgroup\$ – Zsolt Szilagy Aug 11 '20 at 11:57

277 Answers 277

1
6 7
8
9 10
1
\$\begingroup\$

Gol><>, 7 bytes

12K+:N!

Byte knocked off courtesy of JoKing

Try it online!

9 bytes

01T2K+:Nt

Outputs forever with newlines

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ You don't need the leading 0, which means you can just strip out the teleporters and put a skip at the end instead. Try it online!. You can also do 1:@+:N! for the same amount of bytes if you prefer the stack not filling up \$\endgroup\$ – Jo King Oct 17 '19 at 0:54
1
\$\begingroup\$

JVM Byte Code, 79 bytes

The byte count given is for a complete class file that defines a class Code containing single static method Code which implement Fibonacci. A hex dump of the file is given below.

0000000: cafe babe 0003 002d 0004 0100 0428 4929  .......-.....(I)
0000010: 4901 0004 436f 6465 0700 0200 2000 0300  I...Code.... ...
0000020: 0000 0000 0000 0100 0800 0200 0100 0100  ................
0000030: 0200 0000 1800 0400 0100 0000 0c03 045a  ...............Z
0000040: 6084 00ff 1a9d fffa ac00 0000 0000 00    `..............

A helper class is required to invoke the function.

class Test {
    public static void main(String[] args){
        for(int i = 0; i < 20; i++){
            System.out.println(Code.Code(i));
        }
    }
}

Try it online!


The disassembly of the class file with javap -c shows actual byte code implementation of Fibonacci. This requires only 11 bytes, the rest of the 79 bytes in the class file are various header tables that can't be omitted.

class Code {
  static int Code(int);
    Code:
       0: iconst_0
       1: iconst_1
       2: dup_x1
       3: iadd
       4: iinc          0, -1
       7: iload_0
       8: ifgt          2
      11: ireturn
}
\$\endgroup\$
1
\$\begingroup\$

Pyth, 13 bytes

A(Z1)#HA(H+HG

Try it online!

Explanation

A(Z1)#HA(H+HG

 (Z1)           : The tuple (0, 1)
A               : Assign the first value of the tuple to G and the second to H
     #          : Loop until error statement
      H         : Print H
        (H+HG   : The tuple (H, H + G)
       A        : Assign the first value of the tuple to G and the second to H
\$\endgroup\$
1
\$\begingroup\$

Ral, 27 bytes

11=,1*:0*+1=0=1/-:1:+:+?0*.

Try it online!

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

Go 114 113 106 chars

I'm sure this can be improved but I'd like to share my approach using the closed-form expression to calculate Fibonacci numbers.

package main
import(."fmt"
."math")
func main(){for i:=0.0;i<31;i++{Printf("%.0f\n",Pow(Phi,i)/Sqrt(5));}}
\$\endgroup\$
1
\$\begingroup\$

dc, 21 17 bytes

0z[dp_3R+lmx]dsmx

Try it online!

This prints the Fibonacci sequence endlessly.



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

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

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

Actually, 16 bytes

"1,"◙01W;a+;◙',◙

Try it online!

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

GAS x86-64 for Linux (Machine code), 76 68 bytes

Loop-free, because I thought it would be a fun idea. GCC 10.1.

Note/warning: for this to work, you have to turn off DEP and PIE (ASLR). See compilation instructions below.

Look, ma! No loops! Byte count is for the assembled opcodes of func + e + f. Works on 32 bit input. Sure, you'll eventually run out of stack space, but the number will overflow before then. Obviously, a loop would have been much smaller (and easier) to write.

How it works:

  1. Copy payload code to stack-relative space (No modification of %rsp)
  2. Jump to copy destination's start.
  3. Payload calculates the Fibonacci number in %rax and self-unwinds without ever looping
  4. When it's done, return to caller of func

Full testing program:

// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
.global main

message: .asciz "%d"
main:
    mov $N, %rdi
    call func
    mov %eax, %esi
    mov $message, %rdi
    xor %eax, %eax
    call printf
    xor %eax, %eax
    ret

func:
    // We'll take %rdi, but we'll slice it to 32 bits
    // %edi is arg, r8d is our counter.
    mov %edi, %r8d
    // Make 2 copies for arithmetic
    mov %r8d, %eax
    // Set up stack offset
    // N * 32, need 64 bits to work with %rsp
    imul $(eof - e), %eax
    neg %rax
    mov %rsp, %r9
    lea (%rax, %r9), %r9
    // Initialize for Fibonacci
    xor %ebx, %ebx
    xor %eax, %eax
    inc %eax

    // Copy initial payload:
    // Because PIE is turned off, we can use 32-bit addressing for local
    // Stack still seems to be in 64-land, however
    mov $e, %esi
    mov %r9, %rdi
    mov $(eof - e), %ecx
    rep movsb

    // Go to stack offset
    jmp *%r9

e:
    // The payload:
    dec %r8d
    jg f
    ret
f:
    // Do actual Fibonacci stuff
    lea (%ebx, %eax), %edx
    mov %eax, %ebx
    mov %edx, %eax
    // Self-replicate
    mov %r9, %rsi
    mov $(eof - e), %cl
    rep movsb
eof:

I decided on 32-bit input because the stack is not all valid for 64 bits, so we'd run out anyway. It overflows after a we get high enough input, but that's expected.

Compilation:

# Prints 55
# Replace 10 with the input number (1-indexed):
gcc -no-pie -z execstack execstack_fibonacci.sx -DN=10 -g
  • The -z execstack tells the linker to turn off DEP for this program. (Allow the stack to be executable)
  • The -no-pie turns off ASLR.
  • The -DN10 is just easy input control.
  • The -g is for debugging control. Turn it off if you want.

Note: this will NOT work in MinGW because the DEP policy is managed by the OS on Windows. In fact, -z isn't even recognized by MinGW's ld.

Hex dump:

funcs='func e f'
for el in $funcs; do
    echo 'Dump $el'
    gdb -batch -ex "disas/r $el" ./a.out | sed '/^$/d'
done
echo -n "payload size:"
gdb -batch -ex "print eof - e" ./a.out
\$\endgroup\$
1
  • \$\begingroup\$ You may be able to save quite a few bytes here, as there are a lot of unnecessary REX prefixes, and there isn't nearly enough push/pop abuse. \$\endgroup\$ – EasyasPi Jan 16 at 14:56
1
\$\begingroup\$

Javascript, 24 bytes - recursive version, 33 bytes - usage of Binet's formula, 46 bytes - continuous approximation with the "phi" itself

Usage of "Binet's formula" and a bitwise "OR" operator to round the result. Originally in the "Binet's formula" you have to subtract the so-called "smaller phi to the n-th power". "Smaller phi" (-0.618...) is inside the (-1;1) interval, so it gets closer to 0 with each positive power - that's why we can leave it, and just round the meaningful part. Function itself is an anonymous one, declared with the arrow function declaration.

n=>(((5**.5/2+.5)**n)/5**.5)+.5|0

Try it online!

Recursive version - arrow function declaration. Check whether n is less than 3, if so return 1, else do it again (at least) 2 more times, but with an argument of value n-1 and n-2:

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

Try it online!

Continuous approximation. Ni * phi = Ni+1.

WARNING - RUNNING THIS CODE WILL END UP AS AN INFINITE AMOUNT OF ALERTS (next after clicking "ok")

f=n=>{l=n/2+5**.5/2*n+.5|0;alert(l);f(l)};f(1)

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

Flurry, 46 bytes

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

How to run:

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

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

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

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

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

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

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

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

V (vim), 32 bytes

i1
1<esc>qqkyjGp:s:\n:+
C<C-r>=<C-r>"
<esc>@qq@q

(don't)Try it online!

Prints the sequence forever.

Output is not visible on TIO, so here's the first 99 iterations: Try it online!

Last accurate value is \$7540113804746346429\$ after which it exceeds the integer limit.

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

Branch, 18 bytes

1XY[/x#^\yX^+Y10.]

Try it on the online Branch interpreter!

Outputs infinitely. Eventually starts producing garbage values because long long int overflows but that seems to be acceptable.

Explanation

1                   Set the node's value to 1
 XY                 Set the X and Y registers to 1
   [             ]  While value is not 0 (this will always be true in this program)
    /x#             Move to the left child, set to the X register, and output as number
       ^\           Move to the parent and then right child (go to right sibling)
         yX         Set to the Y register, then set the X register to that value
           ^+Y      Move to root, sum the children (X + Y), and set the Y register
              10.   Place 10 and output as character; this also keeps the loop going
\$\endgroup\$
1
\$\begingroup\$

C (clang), 79 70 47 46 bytes

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

Try it online!

Uses a for-loop instead of a while-loop just because I use it more and doing while() gives the same byte count.

Thanks to ceilingcat for golfing 9 bytes. Thanks to Jo King for golfing 23 bytes. Thanks to ceilingcat for golfing another byte.

\$\endgroup\$
1
  • \$\begingroup\$ you can definitely save some bytes combining the first printf into the loop 47 bytes. There's more to be saved with the assignments \$\endgroup\$ – Jo King Jun 4 at 10:31
1
\$\begingroup\$

Knight, 20 19 bytes

;=x=y 1W!Ox=y+x=x y

Try it online!

-1 byte: W1;Ox -> W!Ox

The "print infinitely" variant. (It will eventually overflow).

It is a simple add and swap loop.

Ungolfed:

# init x and y to 1
; = x (= y 1)
# loop forever
# since OUTPUT evaluates to NULL, we
# can just invert the condition 
: WHILE !(OUTPUT x) {
    # Add and swap
    : = y + x (= x y)
}
\$\endgroup\$
1
\$\begingroup\$

COBOL (GNU), 502 bytes

IDENTIFICATION DIVISION.PROGRAM-ID.A.DATA DIVISION.WORKING-STORAGE SECTION.
77 fib1 pic 999.
77 fib2 pic 999.
77 fib3 pic 999.
77 i pic 99.
77 fibst pic XXX.
77 res pic X(64).
PROCEDURE DIVISION.move 0 to i.move 0 to fib1.move 1 to fib2.move "" to res.perform until i greater than 15 add fib1 to fib2 giving fib3 move fib2 to fib1 move fib3 to fib2 move fib1 to fibst string res DELIMITED BY SPACE fibst DELIMITED BY SIZE "," DELIMITED BY SIZE into res add 1 to i end-perform.display res "..."stop run.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This doesn't appear valid because it doesn't output the sequence indefinitely or give the Nth value provided N. \$\endgroup\$ – hyper-neutrino Jun 10 at 19:03
  • \$\begingroup\$ hmm. I will try to solve this. \$\endgroup\$ – smarnav Jun 10 at 19:08
1
\$\begingroup\$

Nim-Lang, 44 bytes, thanks to @Jo King and @caird coinheringaahing:

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

Arbitrary precision version, 106 bytes, thanks to @Jo King and @caird coinheringaahing:

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

C / Objective-c, 62

c;f(a,b){printf("%d ",a+b);if(c++<40)f(a+b,a);}main(){f(0,1);}

This will print the first 40 fibonacci numbers. I assume the compiler will set c=0. If it is trash, than it will not work;

This version is smaller, but it infite show all sequence number

C / Objective-c, 50 (infinite)

f(a,b){printf("%d ",a+b);f(a+b,a);}main(){f(0,1);}
\$\endgroup\$
0
\$\begingroup\$

Python (56 chars)

n=input()
x=5**0.5
print ((1+x)**n-(1-x)**n)/((2**n)*x)

And for the sequence

n=input()
i=1
x=5**0.5
while i<=n:
    print ((1+x)**i-(1-x)**i)/((2**i)*x)
    i+=1
\$\endgroup\$
0
\$\begingroup\$

PHP, Finite - 46 chars

<?for($b=1;$i++<$n;)echo$b-$a=($b+=$a)-$a,"
";

where $n is the length of the sequence

PHP, Infinite - 39 chars

<?for($b=1;;)echo$b-$a=($b+=$a)-$a,"
";
\$\endgroup\$
0
\$\begingroup\$

MATLAB/Octave, n first numbers, 41 39 chars

a=0:1;for(i=3:n);a(i)=a(i-2)+a(i-1);end
\$\endgroup\$
0
\$\begingroup\$

Python 3 (53)

def f(n):
 l,p=0,1
 while n:n,l,p=n-1,p,l+p
 return l
\$\endgroup\$
1
0
\$\begingroup\$

Clojure, 46

(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))

Although, technically 50 since Clojure requires the recur for pseudo tail call:

(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))

Non compressed:

(defn fib [left right iteration]   
  (if (= 0  iteration)
    left
    (fib right (+ right left)  (- iteration 1))))
\$\endgroup\$
0
\$\begingroup\$

Haskell: 27 (21) characters

It almost feels like cheating to use Haskell for something like this. It just prints Fibonacci numbers ad infinitum.

f=1:scanl(+)1f
main=print f

And if using GHCi only 21 characters, including two newlines, are necessary:

Prelude>let f=1:scanl(+)1f
Prelude>f
[1,1,2,3,5,8,13,21...
\$\endgroup\$
1
0
\$\begingroup\$

JAVA - 108 characters:

int[]f={0,1};System.out.println(0);for(int i=0;i<9;i+=2)System.out.printf("%d\n%d\n",f[0]+=f[1],f[1]+=f[0]);
\$\endgroup\$
5
  • \$\begingroup\$ If a space is required in the code, it should be included in the character count. \$\endgroup\$ – Iszi Nov 27 '13 at 21:53
  • \$\begingroup\$ Alright, I will update it. \$\endgroup\$ – user10766 Nov 27 '13 at 21:57
  • \$\begingroup\$ Already fixed it for you - looks like someone approved my edit suggestion. \$\endgroup\$ – Iszi Nov 27 '13 at 22:05
  • \$\begingroup\$ That was me - I went to fix it, and found you had already. \$\endgroup\$ – user10766 Nov 27 '13 at 22:06
  • \$\begingroup\$ Ah. All good, then. Welcome to Code Golf! \$\endgroup\$ – Iszi Nov 27 '13 at 22:10
0
\$\begingroup\$

C 64 Characters

a;main(f,n){scanf("%d",&n);while(--n)f+=a=f-a;printf("%d",f-a);}

This will print the nth Fibonacci number.

A more readable format :

a;
main(f,n){
scanf("%d",&n);
while(--n)
   f+=a=f-a;
printf("%d",f-a);
}
\$\endgroup\$
0
\$\begingroup\$

F#, 63 chars:

let rec g x y n=if n=x then x else f (n-1) y (x+y)
let f=g 0 1
\$\endgroup\$
0
\$\begingroup\$

~-~! (No Comment) - 27

'=|*>~[<'&*-~>+<'&*-~~>]*|:

Didn't think it'd be this short.

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

TI-BASIC - 18 symbols

to print fibonacci sequence starting from 0:

;i
;While 1
;Disp real(Ans
;real(Ans)+imag(Ans)+ireal(Ans
;End

to print fibonacci sequence starting from 1:

;1
;While 1
;Disp real(Ans
;real(Ans)+imag(Ans)+ireal(Ans
;End
\$\endgroup\$
1
  • \$\begingroup\$ real(Ans)-conj(iAns is shorter. \$\endgroup\$ – lirtosiast Aug 8 '15 at 4:23
0
\$\begingroup\$

Ruby - 49 characters

Nobody has done a Ruby solution for the second problem so I thought I'd give that a go:

p Hash.new{|h,k|k<2?k:(h[k-2]+h[k-1])}[gets.to_i]
\$\endgroup\$
0
\$\begingroup\$

Javascript, 53 bytes

a=[1,1];setInterval('a.push(a[b=a.length-1]+a[b-1])')

I decided to use a new approach to create an infinite stream. Works anywhere else but Firefox.

To get the array of integers, simply do a from the console.

\$\endgroup\$
1
6 7
8
9 10

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.