// This program takes in an integer (maxNum) and outputs // every number from 1 to n that is prime. // Algorithm: // INPUT: An integer >= 1 (maxNum) // PROCESS: // 1. Loop from 1 to maxNum: // a) Loop from 2 to the square root of maxNum. // If the current number is divisible by any of these numbers, // then it is not prime. // You don't need to know what this line does (yet!). // It enables us to write information out to file, later in the program. import java.io.*; public class PrimeNumbersSoln { public static void main(String args[]) { // Declare variables int checkNum, possibleDivisor; // Prompt user for maximum value System.out.println("This program will calculate all of the prime " + "numbers from 1 to a number you specify. " + "Please enter a positive number:"); int maxNum = SavitchIn.readInt(); // Check that the input is valid if (maxNum < 1) { System.out.println("Invalid number: " + maxNum + ", exiting."); System.exit(1); // exit(1) signals that an error occurred. } // Echo value back to user System.out.println("Now calculating all of the primes between 1 and " + maxNum); // We want to write out all of the primes to a file (primes.txt) // in the format: // <1 if prime, 0 if not> // (You don't need to understand this file part yet. // But have a look - it will be coming up later.) try { PrintWriter outfile = new PrintWriter(new FileOutputStream("primes.txt")); // PROCESS: Step 1 is to loop over all possible numbers // from 1 to the max for (checkNum=1; checkNum <= maxNum; checkNum++) { // Store whether checkNum is prime here. Initialize it to true. boolean isPrime = true; // Calculate the square root. We'll store this in an int // because our divisors have to be integers and this provides // the largest integer that is <= the true square root. int squareRoot = (int)Math.sqrt(checkNum); // PROCESS: (Your implementation of part 1a) starts here) // Loop over all possible divisors, // from 2 to the square root of checknum for (possibleDivisor=2; possibleDivisor <= squareRoot; possibleDivisor++) { // If checkNum is divisible by something, then it isn't prime. if (checkNum % possibleDivisor == 0) { isPrime = false; } } // If isPrime is still true, then checkNum is prime. if (isPrime) { System.out.println(checkNum + " is prime."); // Write this out to a file. outfile.println(checkNum + " " + 1); } else { outfile.println(checkNum + " " + 0); } } outfile.close(); } catch(IOException e) { System.out.println("Could not create output file."); System.exit(1); } } }