Assignment #76 Collatz Sequence
The counter for the number of steps may be 1 higher than the number. When I made it, I wanted to count the starting number as the first step.
Code
/// Name: Koosha Kimelman
/// Period: 7
/// Program Name: Collatz Sequence
/// File Name: Collatz.java
/// Date Completed: 11/20/15
import java.util.Scanner;
public class Collatz {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int n, x;
x = 1;
String na = "N/A";
System.out.print("Starting number: ");
n = keyboard.nextInt();
System.out.println(n);
if (n != 1 && n > 0) { // This is in case someone chooses 1 (or something lower than it) as their starting number
while (n != 1) {
Thread.sleep(80);
if (n % 2 == 0)
n = n/2;
else if (n % 2 == 1)
n = ((n*3)+1);
System.out.println(n);
x++;
}
System.out.println("It took " + x + " steps to get to 1.");
}
else if (n == 1)
System.out.println("You were supposed to choose a number OTHER than 1.");
else if (n < 1)
System.out.println("You were supposed to choose a number greater than 1.");
}
}
Picture of the output