Fibonacci Program in JavaScript

In this post, we will learn three different ways to find the Fibonacci of given number using JavaScript.
The Fibonacci sequence can be defined as follows:
  • The Fibonacci sequence of 1 or 2 is 1
  • The Fibonacci sequence of n (for n>2) is the Fibonacci of (n-1) + Fibonacci of (n-2)

Using Recursive

function fibonacci(n) {
    if (n < 1) {
        return 0;
    }
    if (n <= 2) {
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log("fibonacci -> " + fibonacci(6));
Output:
fibonacci -> 8

Using Iterative

function fibonacciIterative(n) {
    if (n < 1) {
        return 0;
    }
    let fibNMinus2 = 0;
    let fibNMinus1 = 1;
    let fibN = n;
    for (let i = 2; i <= n; i++) {
        fibN = fibNMinus1 + fibNMinus2;
        fibNMinus2 = fibNMinus1;
        fibNMinus1 = fibN;
    }
    return fibN;
}

console.log(" fibonacci Iterative -> " + fibonacci(6));
Output:
fibonacci Iterative -> 8

Using Memoization

function fibonacciMemoization(n) {
    if (n < 1) {
        return 0;
    }
    const memo = [0, 1];
    const fibonacciMem = num => {
        if (memo[num] != null) {
            return memo[num];
        }
        return (memo[num] = fibonacciMem(num - 1) + fibonacciMem(num - 2));
    };
    return fibonacciMem(n);
}

console.log(" fibonacci Memoization ->  " + fibonacci(6));
Output:
fibonacci Memoization ->  8


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments