Description: Write a function named fib that accepts a number n and return the number of index n
Fibonacci sequence would be something like this: [0, 1, 1, 2, 3, 5, 8, 13, 21, ...]
function fib() {
}
fib(1); // 1
fib(2); // 1
fib(8); // 21
- Write a function to make a Fibonacci sequence
The rule is n = (n - 1) + ( n - 2)
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let arr = [1, 1]; // let's start from 1 not 0
for (let i = 2; i < n; i++) {
arr[i] = arr[i - 2] + arr[i - 1];
}
return arr;
}
console.log(fib(0)); // 0
console.log(fib(1)); // 1
console.log(fib(2)); // [1, 1]
console.log(fib(3)); // [1, 1, 2]
console.log(fib(4)); // [1, 1, 2, 3]
console.log(fib(5)); // [1, 1, 2, 3, 5]
2. Find the index
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let arr = [1, 1]; // let's start from 1 not 0
for (let i = 2; i < n; i++) {
arr[i] = arr[i - 2] + arr[i - 1];
}
return arr[n - 1];
}
console.log(fib(0)); // 0
console.log(fib(1)); // 1
console.log(fib(2)); // 1
console.log(fib(3)); // 2
console.log(fib(4)); // 3
console.log(fib(5)); // 5
console.log(fib(6)); // 8
console.log(fib(7)); // 13
console.log(fib(8)); // 21
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let arr = [1, 1];
let arrIndex = 0;
for (let i = 2; i < n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
arrIndex = i;
}
return arr[arrIndex];
}
console.log(fib(3));
Another answer:
// recursion
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return fib(n - 2) + fib(n - 1);
}
console.log(fib(8));
It must have end condition in recursion, in this case it's if (n === 0) return 0;
and if (n === 1) return 1;