F14Part2.java


Below is the syntax highlighted version of F14Part2.java.


/******************************************************************************
  * Name: Donna Gabai
  * NetID: dgabai
  * Precept: P99
  * 
  * Fall 2014, Programming Exam 1, Collatz Conjecture:
  * This program finds the maximum length of the first N Collatz sequences.
  *  
  * Dependencies: StdOut.java, F14Part1.java
  ****************************************************************************/
public class F14Part2 {
 
    // returns the longest length of the first N Collatz sequences
    public static int maxLength(int N) {
        
        // no sequence can be shorter than Collatz(1) which is length 1
        int max = 1;
        
        // call F14Part1.seqLength() to find length, save max length
        for (int i = 2; i <= N; i++) {
            int length = F14Part1.seqLength(i);
            if (length > max) max = length;
        }
        
        return max;
    }
    
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        
        // find and print the max length of the first N collatz sequences
        StdOut.println(maxLength(N));
    }
}