Skip to content

Instantly share code, notes, and snippets.

@ChrisWhealy
Last active September 25, 2022 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisWhealy/5897fa9585658f491e88fa1f681e56b9 to your computer and use it in GitHub Desktop.
Save ChrisWhealy/5897fa9585658f491e88fa1f681e56b9 to your computer and use it in GitHub Desktop.
Imperative implementation of the Fibonacci function
// Calculate the nth Fibonacci number: imperative style
function fibonacci(n) {
var a = 0, b = 1, sum = 0;
if (n<0) return NaN;
if (n<2) return n;
while (n>1) {
sum = a + b;
a = b;
b = sum;
n = n - 1;
}
return sum;
}
@tarikwaleed
Copy link

fibonacci(1) will return 0, which is not true

@ChrisWhealy
Copy link
Author

Thanks - fixed now

@tarikwaleed
Copy link

Thank your for your effort

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