Skip to content

Instantly share code, notes, and snippets.

@zzarcon
Created February 26, 2016 18:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzarcon/dae3db4b470cb5140fb5 to your computer and use it in GitHub Desktop.
Save zzarcon/dae3db4b470cb5140fb5 to your computer and use it in GitHub Desktop.
Fibonacci loop
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
@shubich
Copy link

shubich commented Jan 14, 2018

Why is your Fibonacci algorithm (0) equal to 1, but not 0?
In other sources I have seen "...while(num >= 1)...".
How it will be correct?

@jason-mcdermott
Copy link

jason-mcdermott commented Sep 15, 2018

@shubich I was wondering the same thing. I guess if you change line 4 to "while (num > 0){" it will be correct.

@DrEVILish
Copy link

DrEVILish commented Jul 26, 2019

This version doesn't require a temp variable
function fibonacci(num) {
var i = 1, j = 0
while (num >= 1) {
j = i + j
i = j - i
num--
console.log(j)
}
//return (j)
}

fibonacci(10)

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