Prime Number Generator


/*
 * Prime Number Generator
 * ======================
 *
 * Description:
 * This Java program generates all the Prime Numbers up to a given
 * value. The value is a command line argument.
 *
 * There are two methods that are used:
 * - Brute force method using modulo division (%)
 * - Sieve of Eratosthenes
 *
 * Inputs:
 * args[0] - Method type
 * 1-Brute force
 * 2-Sieve of Eratosthenes
 * args[0] - End number
 *
 * Outputs:
 * All Prime Numbers up to the End number (args[0])
 *
 * Created By: D. Lee
 * Date: November 2015
 *
 */
 
public class Prime {
  public static void main(String[] args) {
    // Get the parameters from the command line
    int type = Integer.parseInt(args[0]);
    int N = Integer.parseInt(args[1]);
 
    if (type == 1) {
      // Brute force method
      // ------------------
      boolean isPrime = true; // set a flag variable

      for (int i = 2; i < N; i++) {
        for (int j = 2; j <= i/2; j++) { // only need to go halfway to "i"
          if (i%j == 0) {
            isPrime = false;
            break; // Not a prime, so we can exit the loop
          } else {
            isPrime = true;
          }
        }
        // Check isPrime flag
        if (isPrime == true) {
          System.out.print(i + " ");
        }
      }
    } else if (type == 2) {
      // Sieve of Eratosthenes
      // ---------------------
      boolean[] isPrime = new boolean[N+1]; // Create "N+1" elements, just to make it easier to understand
      java.util.Arrays.fill(isPrime, true); // Initialize the isPrime[] array to true
 
      for (int i = 2; i < N+1; i++) {
        if (isPrime[i] == true) {
          // Prime number found, "sieve out" all multiples of that Prime
          System.out.print(i + " ");
          for (int j = i + i; j < N+1; j = j + i) {
            isPrime[j] = false;
          }
        }
      }
    } else {
      System.out.println("Invalid choice");
    }
  }
}