// Marty Stepp, CSE 142, Autumn 2009 // 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.*; // for Scanner public class PrintNumbers { public static void main(String[] args) { printPrimeNumbers(5); printPrimeNumbers(12); printPrimeNumbers(1); printPrimeNumbers(50); } // 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 printPrimeNumbers(int max) { if (max >= 2) { System.out.print(2); for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { System.out.print(", " + i); } } } System.out.println(); // to end the line } // Returns the number of factors of the given integer. // Assumes that n >= 1. public static int countFactors(int n) { int factors = 0; for (int i = 1; i <= n; i++) { // check to see whether i is a factor of n if (n % i == 0) { // i is a factor of n factors++; } } return factors; } }