Javascript Number Type Get k-th Fibonacci number

Introduction

A Fibonacci sequence is a list of numbers that begins with 0 and 1, and each subsequent number is the sum of the previous two.

For example, the first five Fibonacci numbers are:


0 1 1 2 3

If n were 4, your function should return 3; for 5, it should return 5.

Write a function that accepts a number, n, and returns the nth Fibonacci number.

Use a recursive solution to this problem.

example usage:

nthFibonacci(2); // => 1
nthFibonacci(3); // => 2
nthFibonacci(4); // => 3


 const nthFibonacci = function (n) {
   // TODO: implement me!
   const numberList = [0, 1];/*from   ww  w . j av  a 2 s .  co  m*/
   if (n === 0) {
     return 0;
   }
   else if (n === 1) {
     return 1;
   } else {
     while (numberList.length < n + 1) {
       numberList.push(numberList[numberList.length - 1] + numberList[numberList.length - 2]);
     }
     return numberList[numberList.length - 1];
   }
 };

console.log(nthFibonacci(0))
console.log(nthFibonacci(3))
console.log(nthFibonacci(4))
console.log(nthFibonacci(5))
console.log(nthFibonacci(6))
console.log(nthFibonacci(7))



PreviousNext

Related