// CSE 142, Winter 2007 // Author: Martson Limsteppkai // // This program prompts the user for a maximum number and // prints each prime number up to that maximum, followed by // a count of how many primes were printed. // import java.util.*; public class Primes { public static void main(String[] args) { // read max from user Scanner console = new Scanner(System.in); System.out.print("Maximum number? "); int max = console.nextInt(); // print first prime (loop-and-a-half "fencepost" solution) System.out.print(2); // A loop to print the rest of the prime numbers. // We start count at 1 because we already printed 2. // We start i at 3 because we already printed 2. int primes = 1; for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { // i is prime System.out.print(", " + i); primes++; } } System.out.println(); System.out.println(primes + " total primes"); } // Returns how many factors the given number has (including 1 and itself). public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { // i is a factor of number count++; } } return count; } }