Created
August 12, 2016 13:03
-
-
Save wh0am1-dev/f9b1a1b3de74cce567999c1707aa6214 to your computer and use it in GitHub Desktop.
Collatz conjecture calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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