import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; /* Program: PrimeFactors Purpose: Compute the prime factors of an input number. Input: An integer, val. Output: All the prime factors of val (no duplicates), p1, p2, ... pn Preconditions: val > 1 [verified] Postconditions: No two factors are the same, if i != j, pi != pk All the pis are prime. If val is prime, print a message that it is prime. If val <= 1, print a friendly error message. The pi's are all the factors. val = p1^x1 * p2^xn * ... pn^xn for some exponents x1 ... xn. */ public class PrimeFactors { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out, true); while (true){ int val = -1; while (val <= 1) { out.print("Please type a number and I will give you it's prime factors (type 0 to quit): "); out.flush(); try { val = Integer.parseInt(in.readLine()); if (val == 0) return; //0 is to quit if (val <= 1) out.println("You need a number that is greater than 1. Please try again."); } // try catch (Exception e) { out.println("That's not a number. Please try again."); } // catch }//while //prints out a factor of val// int fact = 1; boolean prime = true; // Assume it's prime. do { // Find the next factor fact = factor(val, fact+1); if ((fact != val) && prime) { prime = false; out.print("The factors of " + val + " are:"); } if (fact != 1) out.print(" " + fact); while (val % fact == 0) val = val/fact; } while(val != 1); if (prime) out.print(" is prime"); out.println("."); }//while (true) }//public static void main //procedure returns a number that is a prime factor of val.// static int factor (int val, int startingFactor) { for (int i=startingFactor; i <= Math.sqrt(val); i = i+1) { // System.err.println("Checking factor: " + i); if (val % i == 0) return i; }//for return val; } //factor }//class PrimeFactors