waltermilner

Untitled

Dec 2nd, 2018
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.util.ArrayList;
  2. // Find primes up to 1 million
  3. // Only check for prime factors
  4.  
  5. public class Test {
  6.  
  7.   // primes is prime numbers found so far
  8.   // construct with large initial capacity
  9.   static ArrayList<Long> primes = new ArrayList<>(65536);
  10.  
  11.   public static void main(String[] args) {
  12.     primes.add(2L);primes.add(3L); // start with first 2 primes
  13.     for (long i = 5; i<1000000; i += 2) { // is i a prime?
  14.       // just odd numbers after 3
  15.      
  16.       int n = 1; // index into primes for possible divisor
  17.       long div = primes.get(n); // get possible divisor
  18.       long limit = (long) Math.sqrt(i); // only try up to square root of i
  19.       //System.out.println("Limit = "+limit);
  20.       boolean foundDiv = false; // have we found a divisor yet?
  21.       while (div <= limit && !foundDiv) {
  22.         //System.out.println("Checking div by "+div);
  23.         if (i % div == 0) { // found a divisor
  24.           foundDiv = true;
  25.           continue;
  26.         }
  27.         n++; // go on to next possible divisor
  28.         div = primes.get(n);
  29.       }
  30.       if (!foundDiv) { // add it to list of primes
  31.         primes.add(i);
  32.         System.out.println(i+" is prime");
  33.       }
  34.     }
  35.  
  36.   }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment