EN
JavaScript - Fibonacci sequence (iterative algorithm)
13
points
In this short article, we would like to show how to implement Fibonacci sequence using iterative algorithm in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
function fibonacci(number) {
if(number < 1) {
return NaN;
}
var a = 0;
var b = 1;
for (var i = 1; i < number; ++i) {
var c = a + b;
a = b;
b = c;
}
return b;
}
// Usage example:
console.log(fibonacci(1)); // 1
console.log(fibonacci(2)); // 1
console.log(fibonacci(3)); // 2
console.log(fibonacci(4)); // 3
console.log(fibonacci(5)); // 5