// This program can print all factors of a number (a "fencepost loop") // or count and return how many factors a number has. public class Factors { public static void main(String[] args) { printFactors(24); printFactors(57); System.out.println(countFactors(24)); System.out.println(countFactors(57)); } // counts and returns the number of factors of the given integer public static int countFactors(int n) { int factors = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // a factor! factors++; } } return factors; } // prints the factors of the given integer separated by commas public static void printFactors(int n) { System.out.print("["); for (int i = 1; i <= n - 1; i++) { if (n % i == 0) { // a factor! System.out.print(i + ", "); } } System.out.println(n + "]"); } }