While reading Programming Challenges I thought of implementing the path of 3n+1 for a given number. Here is my first stab in Java. I am not trying to solve the problem, however I thought it is interesting to print the sequence for a given number.
public class ThreeNPlusOne {
public static void main(String[] args) {
ThreeNPlusOne driver = new ThreeNPlusOne();
int counter = 0;
int i = 9;
while (i > 0) {
System.out.print(i + " ");
++counter;
if (i == 1)
break;
i = driver.getNextNumber(i);
}
System.out.println("\nMaxmimum cycle length: " +counter);
}
private boolean isEven(int n) {
return n % 2 == 0;
}
private int getNextNumber(int n) {
if (isEven(n)) {
return n / 2;
}
return (n * 3) + 1;
}
}