// Marty Stepp, CSE 142, Autumn 2010 // This program prints prime numbers up to a given maximum. // The purpose of the program is to demonstrate the idea of // fencepost problems and fencepost loops. import java.util.*; public class PrintNumbers { public static void main(String[] args) { printPrimes(50); printNumbers2(5); printNumbers2(12); printNumbers2(1); } // Prints all prime numbers up to the given max, separated by commas. // If the max is less than 2, a blank line of output is produced. public static void printPrimes(int max) { // post System.out.print(2); for (int i = 3; i <= max; i++) { int f = countFactors(i); if (f == 2) { System.out.print(", " + i); } } System.out.println(); } // Returns the number of factors of the given integer. // Assumes that n >= 1. public static int countFactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { count++; } } return count; } // Prints all numbers 1-n separated by commas. public static void printNumbers(int max) { // post System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); } // Prints all numbers 1-n separated by commas. (second version) public static void printNumbers2(int max) { // post for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); } System.out.println(max); } }