3n+1 path

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;
}
}

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s