Question
By Java program The Fibonacci sequence is a well-known integer sequence that starts with the values 0 and 1 (in that order). Every number after
By Java program
The Fibonacci sequence is a well-known integer sequence that starts with the values 0 and 1 (in that order). Every number after that is the sum of the two previous values in the sequence. For example, 0 and 1 are followed by another 1 (0 plus 1 is just 1), then by 2 (1 plus 1), 3 (1 plus 2), etc. Basically, for all n >= 2, term n is equal to (term n-1 plus term n-2).
The first 10 terms of the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
Write a Java program that prompts the user to enter two (positive) integer values: the total length N of the Fibonacci sequence to generate (assume that this value will always be greater than or equal to 3), and a number P of terms to print (assume this value will always be less than or equal to N). Your program should print the last P terms of the first N terms of the Fibonacci sequence. For example, if the user enters 50 for N and 10 for P, your program should calculate the first 50 terms of the Fibonacci sequence, but only print the last 10 terms (basically, the 41st through 50th values).
Use an ArrayList of integer values (declare its type as ArrayList) to store the Fibonacci sequence (dont forget to prime the ArrayList with the initial values 0 and 1); as you calculate each new term, add it to the end of the ArrayList (Hint: keep going as long as the ArrayLists size is less than N). When you are finished generating the terms of the sequence, use a new loop to retrieve and print the last P terms of that sequence, in order.
For example, if N is 20 and P is 5, your program should print out the values 610, 987, 1597, 2584, and 4181 (which are the last 5 values of the first 20 terms of the Fibonacci sequence).
As a second example, if N is 14 and P is 6, your program should print out 21, 34, 55, 89, 144, 233.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started