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

前端 未结 7 1443
离开以前
离开以前 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 03:02

    There are several things that could be optimized.

    For starters, the "contains" and "removeAll" operations on an ArrayList are rather expensive operations (linear for the former, worst case quadratic for the latter) so you might not want to use the ArrayList for this. A Hash- or TreeSet has better complexities for this, being nearly constant (Hashing complexities are weird) and logarithmic I think

    You could look into the sieve of sieve of Eratosthenes if you want a more efficient sieve altogeter, but that would be besides the point of your question about the 6k +-1 trick. It is slightly but not noticably more memory expensive than your solution, but way faster.

提交回复
热议问题