Factors3.java


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


/******************************************************************************
 *  Compilation:  javac Factors3.java
 *  Execution:    java Factors3 n
 *
 *  Computes the prime factorization of n using brute force.
 *
 *   % java Factors 81
 *   The prime factorization of 81 is: 3 3 3 3
 *
 *   % java Factors 168
 *   The prime factorization of 168 is: 2 2 2 3 7
 *
 *   % java Factors 4444444444
 *   The prime factorization of 4444444444 is: 2 2 11 41 271 9091
 *
 *   % java Factors 4444444444444463
 *   The prime factorization of 4444444444444463 is: 4444444444444463
 *
 *
 *   Can use these for timing tests - biggest 3, 6, 9, 12, 15, and 18 digit primes
 *   % java Factors 997
 *   % java Factors 999983
 *   % java Factors 999999937
 *   % java Factors 999999999989
 *   % java Factors 999999999999989
 *   % java Factors 999999999999999989
 *
 ******************************************************************************/

public class Factors3 {

    public static void main(String[] args) {
        long n = Long.parseLong(args[0]);
        System.out.print("The prime factorization of " + n + " is: ");

        for (long factor = 2; factor <= n; factor++) {
            while (n % factor == 0) {
                System.out.print(factor + " ");
                n = n / factor;
            }
        }
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:12:31 EDT 2022.