Javascript Interview Question Number Get Fibonacci number

Introduction

Write a recursive method to generate nth Fibonacci number.

F(n) = F(n-1) + F(n-1); F(0) == 0, F(1) == 1;

function fibonacci(n) {
    //your code here
}

console.log( fibonacci(42) );//  w w  w  .  j  a v  a  2 s  .  com

/*
Output: ($ /usr/bin/node 010.js)
267914296
*/



function fibonacci(n) {
    if (n === 0) {
        return 0;
    }

    if (n === 1) {
        return 1;
    }

    if (n < 1) {
        return -1;
    }

    return fibonacci(n-1) + fibonacci(n-2);
}

console.log( fibonacci(42) );



PreviousNext

Related