ChengJade2.java

/**
 *  This is a class implements a Java application that finds and prints the
 *  prime factors of a given number.
 *
 *  It uses a recursive method to examine each of the different values of Y.
 *  The value from the recursive method is a void.  It uses a loop to divide X
 *  by Y as many times as needed.  The number X must is specified as the only
 *  command line argument to the program.
 *
 * @author     Cheng Yu
 * @assignment TA 2
 * @date       Jan 28, 2010
 * @bugs       None
 */
public class ChengJade2 {
    /**
     * The entry point of the application.
     *
     * @param args The command line arguments.
     */
    public static void main(final String[] args) {

        // If the command line has anything other than a single integer, the
        // program prints an error message and exits.
        if (args.length != 1) {
            System.err.println("The argument is not a single input.");
            System.exit(1);
        }

        // If the command line input is not an integer, the program prints an
        // error message and exits.
        int x = 0;
        try {
            x = Integer.parseInt(args[0]);
        } catch (final NumberFormatException e) {
            System.err.println("The argument is not an integer.");
            System.exit(2);
        }

        // If the command line input is an integer smaller than 2, the program
        // prints prints an error message and exits.
        if(x < 2) {
            System.err.println("The argument is not an integer greater than 1.");
            System.exit(3);
        }

        // Call the recursive function and print out the prime factors.
        System.out.print(x + "'s prime factors:");
        ChengJade2.findPrimeFactors(x, 2);
        System.out.println();

        // Exit cleanly while debugging from Eclipse.
        System.exit(0);
    }

    /**
     * Finds and print out the prime factor of a specified integer x.
     *
     * @param x the integer to be examined.
     * @param y the prime factors of the integer x.
     */
    private static void findPrimeFactors(int x, final int y) {

        // If y is greater than the square root of x, the next prime factor of
        // x is itself.  Never print a factor of "1".
        if (y > Math.sqrt(x)) {
            if (x != 1)
            System.out.print("\t" + x);
            return;
        }

        // If y is a prime factor, print y. Then dive x by y as many times as
        // needed.
        if (x % y == 0) {
            System.out.print("\t" + y);
            while(x % y == 0)
                x = x / y;
        }

        // Call the function with either modified or original x. Check if the
        // next y is a primer factor.
        findPrimeFactors(x, y + 1);
    }
}
Valid HTML 4.01 Valid CSS