go to previous page   go to home page   go to next page

Answer:

See below.


Complete Program


class Hailstone
{
  static void hail( long N )
  {
    System.out.print( N + ", ");
    if ( N == 1 )
      return;
    else if ( N % 2 == 0 )
      hail( N/2 );
    else
      hail( 3*N+1 );
  }
  
  public static void main ( String[] args )
  {
    long N = Long.parseLong( args[0] );
    hail( N );
  }
  
}

Here is a complete program. The datatype of N is long, so you can play with very big integers. (However, this will flood your screen with numbers. You might want to modify the program so that it prints the length of each sequence, not the individual elements.)

If you happen to find a sequence that does not stop, you will become rich and famous. See Wikipedia for details. Unfortunately, the numbers soon get too big to be handled with datatype long. You will need to modify the program to use the Java class BigInteger if you want to go beyond what has already been tested.

The method prints out the current N, then calls itself with the next N as a parameter. When it hits 1, it returns to its caller, which returns to its caller, and so on until the first activation.

Notice that modulo division is used to determine odd or even. If an integer mod two is one, then the integer is odd.


QUESTION 16:

With some starting Ns, the program soon starts printing out negative numbers. What is going on?