Assignment #76 and Collatz Sequence
Code
/// Name: Ali Kurland
/// Period: 6
/// Program Name: Collatz Sequence
/// File Name: CollatzSequence.java
/// Date Finished: 10/20/2015
import java.util.Scanner;
public class CollatzSequence
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
int n, steps;
steps = 0;
System.out.print( "Starting number: " );
n = keyboard.nextInt();
if ( n <= 0 )
{
System.out.println( "Error - n must be a natural number. Try again." );
System.out.print( "Starting number: " );
n = keyboard.nextInt();
}
System.out.print( n + "\t" );
while ( n != 1 )
{
if ( n % 2 == 0 )
{
n = n/2;
System.out.print( n + "\t" );
steps ++;
}
else
{
n = ((3*n) + 1);
System.out.print( n + "\t" );
steps ++;
}
}
System.out.println( "\n\nTerminated after " + steps + " steps." );
}
}
Picture of the output