Write the Java source code necessary to build a solution for the problem below:
ID: 673296 • Letter: W
Question
Write the Java source code necessary to build a solution for the problem below:
The Fibonacci numbers form a sequence where each number is the sum of the previous two numbers. Starting from 0 and 1, the first eight Fibonacci numbers are built in the following list using the equation Fn = Fn-1 + Fn-2:
0, 0
0, 1
1, 1
1, 2
2, 3
3, 5
5, 8
8, 13
The sequence would be the numbers in red (0, 1, 1, 2, 3, 5, 8, 13).
Using the linked list (MyLinkedList) created in Assignment 3.1, create a stack class and a test program to display the first 50 Fibonacci numbers in descending order. Use a stack to store these numbers. Once 50 numbers have been computed, print the numbers in a descending order. You will note that this process is naturally recursive. Therefore, use recursion to find this series of Fibonacci numbers
Explanation / Answer
public class CrunchifyFibonacci {
@SuppressWarnings("resource")
public static void main(String args[]) {
//input to print Fibonacci series upto how many numbers
System.out.print("Enter number upto which Fibonacci series to print: ");
int number = new Scanner(System.in).nextInt();
System.out.println(" Fibonacci series upto " + number +" numbers : ");
//printing Fibonacci series upto number
for(int i=1; i<=number; i++){
System.out.print(fibonacciRecusion(i) +" ");
}
}
// Java program for Fibonacci number using recursion.
public static int fibonacciRecusion(int number){
if(number == 1 || number == 2){
return 1;
}
return fibonacciRecusion(number-1) + fibonacciRecusion(number -2); //tail recursion
}
// Java program for Fibonacci number using Loop.
public static int fibonacciLoop(int number){
if(number == 1 || number == 2){
return 1;
}
int fibo1=1, fibo2=1, fibonacci=1;
for(int i= 3; i<= number; i++){
fibonacci = fibo1 + fibo2; //Fibonacci number is sum of previous two Fibonacci number
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci; //Fibonacci number
}
}
Output:
Enter number upto which Fibonacci series to print: 15
Fibonacci series upto 15 numbers :
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.