fibonacci numbers nodejs code example
Example 1: how to generate a fibonacci sequence in javascript
// declare the array starting with the first 2 values of the fibonacci sequence
let fibonacci = [0,1];
function listFibonacci(num) {
// starting at array index 1, and push current index + previous index to the array
for (let i = 1; i < num; i++) {
fibonacci.push(fibonacci[i] + fibonacci[i - 1]);
}
console.log(fibonacci);
}
listFibonacci(10);
Example 2: javascript fibonacci example
// number fibonnaci to array format
function fibonacci(nums) {
let fib = [0, 1];
let data = [];
for(let i = 2; i <= nums; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
data.push(fib[i]);
}
return data;
}