Question
- You are given a number n.
- You are required to print the nth element of the Fibonacci sequence.
Note -> Notice precisely how we have defined the Fibonacci sequence
0th element -> 0
1st element -> 1
2nd element -> 1
3rd element -> 2
4th element -> 3
5th element -> 5
6th element -> 8
Input Format
A number n
Constraints
0 <= n <= 45
Sample Input
10
Sample Output
55
Program
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int ans = fib(n, new int[n + 1]);
System.out.println(ans);
}
public static int fib(int n, int[] qb){
if(n == 0 || n == 1){
return n;
}
if(qb[n] != 0){
return qb[n];
}
int fib1 = fib(n - 1, qb);
int fib2 = fib(n - 2, qb);
int fibs = fib1 + fib2;
qb[n] = fibs;
return fibs;
}
}
Comments
Post a Comment
Thanks for the comment.