In this HackerRank Recursion: Fibonacci Numbers Interview preparation kit problem you have Given n, return the nth number in the sequence.


HackerRank Recursion: Fibonacci Numbers interview preparation kit solution


Problem solution in Python programming.

var = [0] *40


def fibonacci(n):
    if n <= 1:
        return n
    if var[n] == 0:
        var[n] = fibonacci(n-1) + fibonacci(n-2)
    return var[n]
    
n = int(input())
print(fibonacci(n))


Problem solution in Java Programming.

import java.util.*;

public class Solution {

    public static int fibonacci(int n) {
    int[] fib = new int[2]; 
    fib[0] = 0; fib[1] = 1;
    for (int i = 2; i <= n; ++i) {
        fib[i % 2] = fib[0] + fib[1];
    }
    return fib[n % 2];
}


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.close();
        System.out.println(fibonacci(n));
    }
}


Problem solution in C++ programming.

#include <iostream>

using namespace std;

int fibonacci(int n) {
    // Complete the function.
    if (n ==0)
        return 0;
    else if (n== 1)
        return 1;
    else 
       return fibonacci(n-1) + fibonacci (n-2);
   
    
}
int main() {
    int n;
    cin >> n;
    cout << fibonacci(n);
    return 0;
}


Problem solution in C programming.

#include <stdio.h>

int fibonacci(int n) {
    
    if (n==0)return 0;
    if (n==1)return 1;
    return fibonacci(n-1)+fibonacci(n-2);

};

int main() {
    int n;
    scanf("%d", &n);
    printf("%d", fibonacci(n));
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    var n = parseInt(input);
    console.log(fibonacci(n));
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function fibonacci(n) {
  return n <= 1 ? n : fibonacci(n - 2) + fibonacci(n - 1);
}