Hi,
Is there a “best practices” way to generate the first n primes? Two ways immediately spring to mind:
Select[Range[n],PrimeQ]
Prime[Range[PrimePi[n]]]
According to my internal picture of “what good Mathematica looks like”, the last one is a whole lot more likely to be faster. However, in real life, it’s not. The first option is considerably quicker, although it does use a bit more memory.
Given the ease of sieving for primes, I’d have thought there would be a better way to do this. Is there a correct way to specify the problem so that Mathematica knows to just return the output of a sieve, rather than having to deal with each prime in turn?
EDITED the first example was erroneously written as Select[Range[PrimePi@n], PrimeQ]
@Shenghui - thanks, I didn’t mean to put the extra PrimePi into the first one (which you evaluated second). @Steven - it’s not as fast as Prime@Range@PrimePi is - presumably because Prime is Listable. The millionth prime is 15485863:
EDIT: After a bit more testing, it does seem like Prime[Range[PrimePi]] is slightly faster, but they seem close enough so that the decision could be made based on personal preference.