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

Answer:

See below.


Complete Program


class Hailstone
{
  public 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 value for N comes from the command line.

C:\JavaCode>javac Hailstone.java
C:\JavaCode>java Hailstone 6
6, 3, 10, 5, 16, 8, 4, 2, 1,

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 hailed as a great programmer. 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.

The remainder operator % is used to determine odd or even. If the remainder after division by 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?


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