In: Computer Science
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).
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.
import java.util.Stack; public class FibonacciDemo { public static long fib(int n) { long result; if (n < 2) { result = n; } else { result = fib(n - 1) + fib(n - 2); } return result; } // end fib public static void main(String[] args) { System.out.println("Wait a second.. It may take a minute of time!"); Stack<Long> numbers = new Stack<>(); for (int i = 0; i <= 50; i++) { numbers.push(fib(i)); } while(!numbers.isEmpty()) { System.out.println(numbers.pop()); } } }
************************************************** Note: It may take upto 2-3 minutes to run this program.. since recursion is quite slow, and we are asked to use plain recursion. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.