Skip to content

Instantly share code, notes, and snippets.

@wh0am1-dev
Created August 12, 2016 13:03
Show Gist options
  • Save wh0am1-dev/f9b1a1b3de74cce567999c1707aa6214 to your computer and use it in GitHub Desktop.
Save wh0am1-dev/f9b1a1b3de74cce567999c1707aa6214 to your computer and use it in GitHub Desktop.
Collatz conjecture calculator
public class Collatz {
public static void main(String[] args) {
String input;
System.out.println("Press ctrl+c to quit\n");
while (true) {
try {
System.out.print("> ");
int n = Integer.parseInt(System.console().readLine());
int i = 0;
while (n != 1) {
System.out.print(n + " ");
n = step(n);
i++;
}
System.out.println(n + "\n\nIterations = " + i + "\n\n===============\n");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException\n\n===============\n");
}
}
}
public static int step(int n) {
if (n <= 0) return 1;
else if (n % 2 == 0) return n / 2;
else return n * 3 + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment