Question
The Hailstone sequence ( HYPERLINK https://plus.maths.org/content/mathematical-mysteries-hailstone-sequences https://plus.maths.org/content/mathematical-mysteries-hailstone-sequences) is an algorithm that starts with a positive integer and then, through a series of changes ends up
The Hailstone sequence ( HYPERLINK "https://plus.maths.org/content/mathematical-mysteries-hailstone-sequences" https://plus.maths.org/content/mathematical-mysteries-hailstone-sequences) is an algorithm that starts with a positive integer and then, through a series of changes ends up with (hopefully) a never-ending sequence of 4-2-1.
WRITE A JAVA PROGRAM TO DO THE HAILSTONE ALGORITHM
Your algorithm will be a separate class. When constructed it should be passed a positive Long integer and an ArrayList to store the values generated. It will verify that the integer is greater than zero (changing it to a 1 if it is not) , then call a recursive method that creates and stores in the ArrayList the hailstone sequence until the number 1 is reached.
For any n>1,
If n is even, divide it by two and repeat
If the number is odd, multiply by three and add one, then repeat
The ArrayList parameter will have a record of the complete sequence of numbers generated. For example, if called with 5 the list would contain [ 5, 16, 8, 4, 2, 1].
Your driver program will save each such sequence in an ArrayList (so you will have an ArrayList of ArrayLists) after looping through the numbers specified by the user.
The Driver will begin by asking the user to enter a positive integer. (This is just an integer, we are using long integers above because we dont know how big they might get.) It will then enter a counting loop from 1 to the number entered. For each index value, it will create a HailStone object, passing it both the index and an ArrayList to receive the values.
HailStone will have a separate method to do the actual calculations. It may be called from the HailStone constructor or your Driver, as you see fit.
At the end of your counting loop, you will have a data set that you know nothing about. (The list of lists.)
Determine which of the sequences is longest. Note this is done after all the data is stored, not while the data set is being created (post-processing).
Provide explanatory output (see example).
Use a recursive display method to repeatedly delete the first element in the sequence and show it on the console, until the list is empty.
The latter is pretty simple and may be implemented as a static function that is called from main().
SAMPLE CONSOLE:
Enter the largest number: 20
The longest sequence was 21 starting with 18
18
9
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered 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