Prime Number Generator Logic

后端 未结 15 2227
旧时难觅i
旧时难觅i 2021-01-07 04:10

I am supposed to make a class PrimeNumberGenerator which has a method nextPrime that will print out all prime numbers up to a number the user input

15条回答
  •  隐瞒了意图╮
    2021-01-07 05:02

    Doing primality check on each and every number is inefficient in your case. Use Sieve_of_Eratosthenes instead, to find all prime numbers up to any given limit.

    public class PrimeGenerator {
    
      private final BitSet primes;
    
      private int nextPrime = 0;
    
      /**
       * Sieve of Eratosthenes
       */
      public PrimeGenerator(final int LIMIT)
      {
        primes = new BitSet(LIMIT+1);
        primes.set(2, LIMIT);
    
        for (int i = 4; i < LIMIT; i += 2)
          primes.clear(i);
    
        final int SQRT = (int) Math.sqrt(LIMIT);
        for (int p = 3; p <= SQRT; p = primes.nextSetBit(p+2)) {
          for (int j = p * p; j <= LIMIT; j += 2 * p) {
            primes.clear(j);
          }
        }
      }
    
      public int nextPrime()
      {
        nextPrime = primes.nextSetBit(nextPrime + 1);
        return nextPrime;
      }
    
      public static void main(String[] args) {
        // print primes up to 1000
        PrimeGenerator primeGen = new PrimeGenerator(50);
        int prime = primeGen.nextPrime();
        while (prime != -1) {
          System.out.println(prime);
          prime = primeGen.nextPrime();
        }
      }
    }
    

    Optimization tips when implementing Sieve of Eratosthenes:

    • Iterate only over the odd numbers. Because all the multiples of 2, except for 2 is composite.

    • Start eliminating from (p * p). So for instance for the prime number 3, you should start eliminating from 9.

    • Increment by 2 * p instead of p, so to avoid even numbers.

    This could generate millions of primes in just seconds.

提交回复
热议问题