// Marty Stepp, CSE 142, Autumn 2008 // This program contains various methods for printing numbers. // It demonstrates "fencepost problems" where you want to print // n numbers separated by n-1 spaces, commas, etc. import java.util.*; public class PrintNumbers { public static void main(String[] args) { printNumbers(5); printNumbers(12); printNumbers(1); printPrimes(50); } // Prints all prime numbers up to the given maximum integer. // For example, printPrimes(50) prints: // [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 50] public static void printPrimes(int max) { System.out.print("[2"); for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { System.out.print(" " + i); } } System.out.println("]"); } // Returns the number of factors of the given integer n. // For example, countFactors(60) returns 12 because 1, 2, 3, 4, 6, // 8, 10, 12, 15, 20, 30, and 60 are factors of 60. // Assumes that n > 0. public static int countFactors(int n) { // check every integer i from 1--n, // see if i is a factor of n int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // i is a factor of n count++; } } return count; } // Prints the numbers 1-n separated by commas. // For example, printNumbers(5) prints 1, 2, 3, 4, 5 public static void printNumbers(int n) { for (int i = 1; i < n; i++) { System.out.print(i + ", "); } System.out.println(n); } // Alternative solution to printNumbers public static void printNumbers1(int n) { System.out.print(1); for (int i = 2; i <= n; i++) { System.out.print(", " + i); } System.out.println(); } }