Mathematica - generate a list of primes to the limit

What is the simplest function that generates a list of primes before an argument? It’s not difficult to come up with such a function, for example:

foo[n_] := Block[{A = {}, p = 2}, While[p < n, A = Append[A, p]; p = NextPrime[p]]; A] 

However, this seems too dirty. I would like to do something like

 foo[n_] := Table[Prime[i], {i,2,???}] 

Where??? is the NextPrime[n,-1] index NextPrime[n,-1] . Is it possible?

+6
source share
3 answers

for instance

 f[x_] := Prime[ Range@PrimePi @x] 

Using

 Grid[Table[{x, f[x]}, {x, 13, 20}], Frame -> All] 

Mathematica graphics

+6
source

My favorite form:

 p = Prime ~Array~ PrimePi@ # &; p @ 20 

{2, 3, 5, 7, 11, 13, 17, 19}

+2
source

One of the common algorithms for this is the Sieve of Eratosthenes . This is a simple algorithm and reasonably easy to implement in any language.

0
source

Source: https://habr.com/ru/post/922140/


All Articles