Skip to content

Instantly share code, notes, and snippets.

@kassens
Forked from 140bytes/LICENSE.txt
Created May 23, 2011 11:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kassens/986590 to your computer and use it in GitHub Desktop.
Save kassens/986590 to your computer and use it in GitHub Desktop.
Fibonacci in 52 bytes.
function(n){ // calculate the nth fibonacci number
for(
var a = 0, b = 1; // start with a = 0 and b = 1
n--; // run the loop n times
) b = a + (a = b); // assign a = b and b = a + b 'in parallel'
return a // return the result
}
function(n){for(var a=0,b=1;n--;)b=a+(a=b);return a}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jan Kassens <jan@kassens.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "fibonacci",
"description": "Fibonacci in 52 bytes.",
"keywords": [
"140bytes",
"fibonacci",
"math"
]
}
@Pet3ris
Copy link

Pet3ris commented May 26, 2011

The last semicolon is not necessary, I think. A recursive version would probably be shorter, but I'm sure you didn't choose it for speed/memory reasons.

@kassens
Copy link
Author

kassens commented May 26, 2011

@Pat3ris: good catch with the semicolon. Since the outer function should be anonymous, defining an inner function is most likely longer.

@p01
Copy link

p01 commented May 27, 2011

Very nice job with b=a+(a=b)
A recursive approach respecting the rules of 140byt.es is around 62 bytes

@williammalo
Copy link

save 2 bytes:
function(n,a,b){for(b=1;n--;)b=~~a+(a=b);return a}

@p01
Copy link

p01 commented Apr 11, 2012

facepalm How did we miss that ? Well done!

@rhysbrettbowen
Copy link

function(n,a,b){for(a=0,b=1;n>1;n-=2,b+=a+=b);return n?b:a;};

longer but even faster (does two steps per loop so two assignments for two steps rather than two for one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment