/** * * @author inoxor */ import java.io.*; public class Assignment1 { public static void main(String[] args) { long timeBegin = System.nanoTime(); int limit = 10000000; int primes = 0; boolean[] isPrime = new boolean[limit+1]; // initializes as false for(int i = 2; i*i <= limit; i++) { if(!isPrime[i]) { for(int j = i; j*i <= limit; j++) // eliminate i^2 and multiples of it isPrime[i*j] = true; // we use true to mark non-primes } } PrintWriter out = null; try { out = new PrintWriter("primes.txt"); // printwriter does not flush by default for(int i = 2; i <= limit; i++) { if(!isPrime[i]) { out.println(i); primes++; } } } catch(IOException e) { System.out.println(e); } finally { if(out != null) out.close(); // flush & close } long estimatedTime = System.nanoTime() - timeBegin; System.out.println("Execution took " + estimatedTime/1000000 + " ms. Found " + primes + " primes."); } }