Assignemnt #76 Collatz Sequence
Code
Name: Iaroslav Titov
Period: 7
Project Name: Collatz
File Name: Collatz.java
Date: 1/11/2015
import java.util.Scanner;
import java.util.InputMismatchException;
public class Collatz
{
public static void main( String[] args ) throws Exception
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number to start the Collatz sequence with.\n");
int counter = 0;
int num = 0;
try
{
System.out.print("Starting number: ");
num = keyboard.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("WRONG INPUT!!!");
}
while (num != 1)
{
System.out.print(num);
for (int i = 0;i < 10 - Integer.toString(num).length();i++)
System.out.print(" ");
if (num % 2 == 0) num /= 2;
else num = num*3+1;
counter++;
if (counter % 10 == 0) System.out.print("\n");
}
System.out.println(num);
System.out.println("It took "+counter+" iterations to arrive to 1.");
}
}
Picture of the output