Assignment #76: Collatz Sequence
Code
/// Name: Kiran O'Farrell
///Program Name: Collatz Sequence
/// File Name: Collatz.java
/// Date Completed: 3/9/16
import java.util.Scanner;
public class Collatz {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
int n;
int steps = 0;
System.out.println("What number would you like to test a Collatz sequence for?");
n = kb.nextInt();
while (n != 1) {
if (n % 2 == 0 && (n != 1)) {
n = n / 2;
System.out.println(n);
steps++;
}
if (n % 2 == 1 && (n != 1)) {
n = ((3 * n) + 1);
System.out.println(n);
steps++;
}
}
if (n == 1) {
System.out.println("There were " + steps + " steps.");
}
}
}
Picture of the output