/**
* This is a class implements a Java application that finds and prints the prime
* factors of a given number.
* <ul>
* <li>it uses a recursive method to examine each of the different
* values of Y.</li>
* <li>the value from the recursive method is a void.</li>
* <li>it uses a loop to divide X by Y as many times as needed.</li>
* <li>the number X must is specified as the only command line argument to the
* program.
* </ul>
*
* @author Cheng Yu
* @assignment TA 2 Part 1
* @date Sep 7, 2008
* @bugs None
*/
public class ChengJade02 {
/**
* The entry point of the application.
*
* @param args
*/
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
// 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:");
ChengJade02.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 out 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 out y. Then dive x by y as many times as
// needed.
if (x % y == 0) {
System.out.print("\t" + y);
do {
x /= y;
} while (x % y == 0);
}
// Call the function with either modified or original x. Check if the next
// y is a primer factor.
ChengJade02.findPrimeFactors(x, y + 1);
}
}