Assignment # 76 and Collatz Sequence
Code
/// Name: Tommy Oyuntseren
/// Period: 7
/// Program Name: Collatz
/// File Name: Collatz.java
/// Date: 1/26/2016
import java.util.Scanner;
public class Collatz
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner(System.in);
int n;
int steps=0;
System.out.print("Starting number: ");
n=keyboard.nextInt();
while (n<=0)
{
System.out.println(n + "is not a natural number. Try again.");
n=keyboard.nextInt();
}
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