// CSE 142, Autumn 2007, Marty Stepp // // This program reads two integers from the user, // prints how many factors the numbers have and whether they are prime, // and whether they have the same number of factors or not. // (We didn't finish this in the 9:30 Section A.) import java.util.*; // for Scanner public class Factors2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("This program compares factors of two numbers."); System.out.println(); int factors1 = processNumber(console); int factors2 = processNumber(console); if (factors1 == factors2) { System.out.println("They have the same number of factors."); } else { System.out.println("They have a different number of factors."); } } // Reads a number, counts its factors, tells whether it is prime, // and returns the number of factors. public static int processNumber(Scanner console) { System.out.print("Type a number: "); int num = console.nextInt(); int factors = countFactors(num); System.out.println(num + " has " + factors + " factors."); if (factors <= 2) { System.out.println(num + " is prime."); } else { System.out.println(num + " is not prime."); } System.out.println(); return factors; } // Counts and returns how many the factors the given number has, and // prints whether the number is prime. public static int countFactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // i is a factor of n count++; } } return count; } }