CSC 221: Computer Programming I
Fall 2004

HW3: Counters and Repetition


An interesting unsolved problem in mathematics concerns what is called the "hailstone sequence." This sequence is defined as follows: Start with any positive integer. If that number is odd, then multiply it by three and add one. If it is even, divide it by two. Then repeat.

For example, starting with 5 we get the hailstone sequence:

5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, ...

Here, the subsequence 4,2,1 is reached, resulting in a loop. It is conjectured that no matter what number you start with, you will always end up in the 4,2,1 loop. It has, in fact, been shown to hold for all starting values up to 1,200,000,000,000. However, the conjecture still has not been proven to hold for all numbers.

Define a class named Hailstone that allows the user to generate and view hailstone sequences. The class should have a method named showSequence with one parameter (the starting number in the hailstone sequence). When called, the method should display each number in the sequence on a separate line. If the sequence gets to 1 (meaning it is stuck in the 4,2,1 loop), then showSequence should print out the word "STUCK!", followed by the length of the sequence. For example, a call to showSequence with input value 5 should produce:

    5
    16
    8
    4
    2
    1
    STUCK!

    Hailstone sequence length: 6

Since hailstone sequences are only defined for positive numbers, the showSequence method should simply display an error message if called with a non-positive input value.

In addition to displaying hailstone sequences, your Hailstone class should also keep track of the longest sequence it has encountered. That is, it should have a field for storing the longest sequence, which initially is zero. Then, each time a new sequence is generated, its length should be compared with the longest so far, and the field updated if necessary. An accessor method named getLongestSoFar should be provided to allow the user to view this length.

Once your class is completed, answer the following questions:

  1. What is the smallest starting number that generates a hailstone sequence with length at least 15?
  2. Identify a starting number for which the hailstone sequence has length at least 30. What is the length of the sequence? What are the lengths of the sequences starting at the numbers one smaller and one larger?
  3. If the starting number N has a hailstone sequence of length L, what would be the length of the hailstone sequence starting at 2N? Explain your reasoning.
  4. Describe an infinite class of numbers for which a hailstone sequence is strictly decreasing. That is, starting with a number of that form, the numbers in the sequence never get bigger. Explain your reasoning. Hint: what kind of number can repeatedly be divided by two?