InterviewSolution
Saved Bookmarks
| 1. |
Write a program in Java to generate the Nth Fibonacci Number using Iteration and Constant Space. |
|
Answer» Fibonacci Series is a series in which the Nth term is the sum of the previous 2 terms i.e. (N-1)th and (N-2)th terms. The first 2 terms of the Fibonacci sequence are always known. They are 0 and 1 respectively. After this, the further terms can be generated as follows: So, in general, we can derive a generic term i.e.
So, let us now write a program to find the Nth Fibonacci Number using iteration. a. Java Program to generate Nth Fibonacci Number using Iteration. import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int a = 0; //0th fibonacci number int b = 1; //1st fibonacci number if(n < 0) { System.out.println("N cannot be negative"); return; } if(n == 0) System.out.println(a); else if(n == 1) System.out.println(b); else { int c = 0; for(int i=2;i<=n;i++) { c = a + b; a = b; b = c; } System.out.println(c); } } } Sample Input/Output: Run Code Input: 7Output: 13
|
|