For a library, I need to store the first primes numbers up to a limit L. This collection must have a O(1) lookup time (to check whether a number is prime or not) and it must
Given that memory is so cheap, I don't think you can do much better from a speed perspective than your existing scheme.
If there's a better solution, then I'd assume it'd take advantage of the Prime Number Theorem that shows that as L gets bigger, the limit of
π(L) / (L / ln(L)) approaches 1.
Perhaps a better solution would have an adaptive packing solution in a data structure sort of like a skip list.
At the moment you are treating 2 as special case and then having an array where every odd number is mapped to an element in the array (with some odd numbers being prime). You could improve on this by treating 2 and 3 as special cases recognising that the rest of the prime numbers are in the form 6n+1 or 6n-1 (that is for all primes p where p > 3, p mod 6 = 1 or 5). This can be further generalised - see Wikipedia. For all primes p > 5, p mod 30 = 1, 7, 11, 13, 17, 19, 23 or 29. You could keep going with this and reduce the memory needed at the expense of processing time (although it will still be O(1), just a slower O(1)).
How about some kind of hash table?
You would need a very good hash function (something like n mod p
, where p
is not a multiple of any of the q
lowest primes - choose q
sufficiently high in order to minimise the number of collisions).