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:
xxxxxxxxxx
1
function fibonacci(number) {
2
if(number < 1) {
3
return NaN;
4
}
5
var a = 0;
6
var b = 1;
7
for (var i = 1; i < number; ++i) {
8
var c = a + b;
9
a = b;
10
b = c;
11
}
12
return b;
13
}
14
15
16
// Usage example:
17
18
console.log(fibonacci(1)); // 1
19
console.log(fibonacci(2)); // 1
20
console.log(fibonacci(3)); // 2
21
console.log(fibonacci(4)); // 3
22
console.log(fibonacci(5)); // 5