import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; /** * A program that reads integers and provides their prime factors. */ public class PFac { public static void main(String[] args) throws Exception { // Prepare for input and output. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out, true); // Get input out.print("Enter a number and I will try to give you its prime factorization: ") ; out.flush() ; try // Input of an integer may fail { int num = Integer.parseInt(in.readLine()) ; if (num<=1) out.println ("Error: Does not compute.") ; else { // Determine if num is prime. double limit = Math.sqrt(num); boolean prime = true; for (int i=2 ; i <= limit && prime; i++) { if (num % i == 0) prime = false; } if (prime) out.println (num + " is prime."); else { out.print ("Prime factors are"); int test = 2; // Repeatedly divide number by possible factors until you // know you can't divide it any more. while (num!=1) { // If it's evenly divisible if (num % test == 0) { // Remove all factors while (num % test == 0) num = num / test; // Print the factor out.print (" " + test); } //if // Move on to the next factor test = test+1; } //while test out.println ("."); } // num is not prime } // num is not negative } //try catch (Exception e) { out.println ("That's not an integer."); } }// main }// class PFac