How do I generate Primes Using 6*k +- 1 rule

前端 未结 7 1439
离开以前
离开以前 2021-02-04 02:07

We know that all primes above 3 can be generated using:

6 * k + 1
6 * k - 1

However we all numbers generated from the above formulas are not pr

7条回答
  •  别跟我提以往
    2021-02-04 02:38

    You can generate your trial numbers with a wheel, adding 2 and 4 alternately, that eliminates the multiplication in 6 * k +/- 1.

    public void primesTo1000() {
      Set notPrimes = new HashSet<>();
      ArrayList primes = new ArrayList<>();
      primes.add(2);  //explicitly add
      primes.add(3);  //2 and 3
    
      int step = 2;
      int num = 5  // 2 and 3 already handled.
      while (num < 1000) {     
        handlePossiblePrime(num, primes, notPrimes);
        num += step;      // Step to next number.
        step = 6 - step;  // Step by 2, 4 alternately.
      }
      System.out.println(primes);
    }
    

提交回复
热议问题