Factors2.java


Below is the syntax highlighted version of Factors2.java from §1.3 Conditionals and Loops.


/*************************************************************************
 *  Compilation:  javac Factors2.java
 *  Execution:    java Factors2 N
 *  
 *  Semantic errors
 *  ---------------
 *
 *  % javac Factors 2
 *  % java Factors2 34
 *  Exception in thread "main" java.lang.ArithmeticException: / by zero
 *          at Factors2.main(Factors2.java:16)
 *
 *  Start i loop at 2
 *  -----------------
 *  % java Factors2 49
 *  3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ...
 *
 *  Include curly braces around while block
 *  ---------------------------------------
 *  % java Factors2 49
 *  7 7
 *
 *  % java Factors2 17
 *  [no output]
 * 
 *  End i loop at N instead of N-1
 *  ------------------------------
 *  % java Factors2 17
 *  17
 *
 *
 *
 *************************************************************************/

public class Factors2 {
   public static void main(String[] args) {
      long N = Long.parseLong(args[0]);
      for (long i = 0; i < N; i++) {
         while (N % i == 0)
            System.out.print(i + " ");
            N = N / i;
      }
   }
}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.