Factors1.java


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



/*************************************************************************
 *  Compilation:  javac Factors1.java
 *  Execution:    java Factors1 N
 *  
 *  Syntax errors
 *  -------------
 *    - forgot to declare variable i
 *    - forgot to terminate statements with semicolons
 *    - forgot to use curly braces to delimit inner block
 *
 *  % javac Factors1.java
 *  Factors1.java:16: ';' expected
 *        for (i = 0; i < N; i++) {
 *        ^
 *  1 error
 * 
 *  Declare i as type long
 *  ----------------------
 *  % javac Factors1.java
 *  Factors1.java:32: ';' expected
 *        for (long i = 0; i < N; i++) {
 *        ^
 *  1 error
 *
 *
 *  Add semicolons
 *  --------------
 *
 *  % javac Factors1.java
 *  %  java Factors1 34
 *  Exception in thread "main" java.lang.ArithmeticException: / by zero
 *          at Factors1.main(Factors1.java:23)
 *
 *
 *************************************************************************/

public class Factors1 {
   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.