// This file demonstrates writing data to a text file using
// the PrintWriter class and the File class
//
//  -- M. Branicky, 10/09/06, 10/07/07

import java.io.PrintWriter; // needed for output processing using PrintWriter
import java.io.File;        // needed for file input/ouput

public class PrimeFinder2 {
  public static void main(String args[]) throws Exception {  // NOTE change here
    int i;
    final int NUMPRIMES = 250000, PRINTEVERY = 10000;
    int prime [] = new int [NUMPRIMES];

    // Find the first NUMPRIMES primes
    i = 2;
    int numFound = 0;
    while (numFound < NUMPRIMES) {
      if (isPrime(i)) {
        prime[numFound]=i;
        numFound = numFound + 1;
        if (numFound%PRINTEVERY==0) System.out.println("Found "+numFound+"...");
      }
      i = i + 1;
    }

    // Open the file and create the PrintWriter
    File outfile = new File("primes.txt");
    PrintWriter output = new PrintWriter( outfile );

    System.out.println("Writing file ...");
    // Write the output
    for (i=0; i<NUMPRIMES; i++) {
      output.println((i+1)+"\t"+prime[i]);
    }
    System.out.println(".. done writing file.");

    // Close the file
    output.close();
  }

  // returns true if n>=2 is prime; false, otherwise
  public static boolean isPrime (int n) {
    int i;

    if (n < 2) { return false; }  // prime must be >=2
    i = 2;
    // test factors up to, and including, the square root of n
    while (i*i <= n) {
      // if i evenly divides n, n isn't prime
      if (n%i == 0) { return false; }
      i = i + 1;
    }
    return true;
  } 

}
