// CSE 142, Autumn 2007, Marty Stepp // // This program demonstrates fencepost loops and boolean logic // in methods about counting and printing factors of an integer. import java.util.*; // for Scanner public class Factors3 { public static void main(String[] args) { printFactors(24); printFactors2(24); Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); if (isPrime(number)) { System.out.println(number " is a prime number."); } else { System.out.println(number " isn't prime."); } } // Prints the factors of the given number. // For example, printFactors(24) prints [1, 2, 3, 4, 6, 8, 12, 24]. // This is an example of a fencepost problem. public static void printFactors(int n) { System.out.print("[" + 1); for (int i = 2; i <= n; i++) { if (n % i == 0) { // i is a factor of n System.out.print(", " + i); } } System.out.println("]"); } // Prints the factors of the given number, other than 1 and n itself. // For example, printFactors(24) prints [2, 3, 4, 6, 8, 12]. // This is another example of a fencepost problem. public static void printFactors2(int n) { System.out.print("["); int count = 0; for (int i = 2; i <= n - 1; i++) { if (n % i == 0) { // i is a factor of n count++; if (count > 1) { System.out.print(", " + i); } else { System.out.print(i); } } } System.out.println("]"); } // Returns true if the given number is prime, or false if not. public static boolean isPrime(int n) { if (countFactors(n) == 2) { return true; } else { return false; } } // Returns how many factors the given number has. // Assumes n is non-negative. 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; } }