/* Collatz * * Famous unsolved problem in number theory, known as the Collatz problem. * This program prints the number less than N(runtime argument) that has the * largest number of iterations through collatz(), and then prints that * number. * * * %javac Collatz.java * * %java Collatz 3 * Value of n for which n < N # of recursive calls for collatz(n) is maximized: 2 * Value of # of recursive calls: 2 * * java Collatz 7 * Value of n for which n < N # of recursive calls for collatz(n) is maximized: 6 * Value of # of recursive calls: 9 * * * java Collatz 846 * Value of n for which n < N # of recursive calls for collatz(n) is maximized: 703 * Value of # of recursive calls: 171 * * * CIS201-L UAB SUMMER 2014 Dr. Sloan * http://introcs.cs.princeton.edu/java/23recursion/Collatz.java.html * * @author * Dan Latham * * @version 0.0.1 * */ public class Collatz { public static int strip(String word) { int length = word.split(" ").length; return length; } public static String collatz(int n, String word) { if (n == 1) return word; else if (n % 2 == 0) { word = word+" "+n/2; //System.out.println(word); word = collatz(n / 2, word); } else { word = word+" "+(3*n+1); //System.out.println(word); word = collatz(3*n + 1, word); } return word; } public static void main(String[] args) { int n = Integer.parseInt(args[0])-1; int placeholder_n = n; int placeholder_length = 0; String word = ""; while (n > 1) { word = collatz(n, String.format("%s", n)); //DEBUG System.out.println(word); int z = strip(word); if (z > placeholder_length) { placeholder_length = z; placeholder_n = n; } n -= 1; } //DEBUG System.out.println(word); System.out.println("Value of n for which n < N # of recursive ca"+ "lls for collatz(n) is maximized: "+ placeholder_n); System.out.println("Value of # of recursive calls: "+ placeholder_length); } }