Given an integer N, find the Nth number in the fibonacci series. Consider 0 and 1 to be the seed values.
In a fibonacci series, each number ( Fibonacci number ) is the sum of the two preceding numbers. The series with 0 and 1 as seed values will go like –
0, 1, 1, 2, 3, 5…..
Input:
User Task: You have to take input integer N as a parameter.
Constraints:
1 ≤ N ≤ 30
Output:
Print the Nth Fibonacci number.
Example:
Input: 1 Output: 0
Input: 2 Output: 1
Input: 5 Output: 3
Solution of Recursive Fibonacci:–
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int fibonaci=fib(n); System.out.print(fibonaci); } public static int fib(int n){ if(n==1) { return 0; } if(n==2) { return 1; } return fib(n-1)+fib(n-2); } }
Add a Comment