Basically, we have to create a program which will output the hailstone numbers for an initial integer value between 1 and 200. That part I've done, the code is here:
import java.util.Scanner;
public class Hailstone1
{
public static void main(String[] args)
{
int initial_value;
int calculated_num = 1;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please input an integer between 1 and 200: ");
initial_value = input.nextInt();
if(initial_value < 1 || initial_value > 200)
{
System.out.println("Invalid number. Please try again.");
}
}while(initial_value < 1 || initial_value > 200);
while(initial_value >= 1)
{
if(initial_value % 2 == 0)
{
initial_value /= 2;
}
else
{
initial_value = (initial_value * 3) + 1;
}
calculated_num ++;
if(calculated_num % 9 == 0)
{
System.out.println(initial_value);
}
else
{
System.out.print(initial_value + " ");
}
}
}
}
However, the next part of the question asks
What is the maximum number of iterations to reach the cycle and which starting number produces this maximum?
I'm not sure how to incorporate this into my code or even where to incorporate it as the program will just keep looping the 4, 2, 1, 4, 2, 1... sequence everytime it is reached so the program will never even be able to output the number of iterations to reach the cycle of 4, 2, 1, 4, 2, 1....
*****************
This was the content of the original question (if it's of any use):
An interesting yet unsolved question in mathematics is called "hailstone numbers". This series is produced by taking an initial integer, and if the number is even, dividing it by 2. If the number is odd, multiply it by 3 and add 1. This process is then repeated. For example, an initial number of 10 produces:
10, 5, 16, 8, 4, 2, 1, 4, 2, 1...
An initial value of 23 produces:
23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1...
Note that both numbers eventually reach the 4, 2, 1, 4, 2, 1... cycle. Create two applications (Hailstone1 and Hailstone2) that answer the following questions for initial values of 1 to 200:
a) Do all integers from 1 to 200 eventually reach this cycle?
b) What is the maximum number of iterations to reach the cycle and which starting number produces this maximum?>
******************
Thanks for any help!
Edited by: DMNT on Feb 5, 2009 10:04 AM