Sign up ×

What is the simplest function that generates a list of primes up to the argument? Its not hard to come up with such a function, for instance:

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

However, this seems overly messy. I would like to do something like

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

Where ??? is the index ofNextPrime[n,-1]. Is this possible?

share|improve this question
You may be interested to know that there is a Mathematica-specific StackExchange site. When programming in Mathematica, it is always good to check all uses of While, For, Do and Append. They are hangovers from other languages and (as the answers below show), there are usually more concise approaches in Mathematica. – Verbeia Aug 8 '12 at 9:44

3 Answers 3

up vote 6 down vote accepted

For example

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


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

Mathematica graphics

share|improve this answer
Thanks. The part I was missing (I called it ???, basically the inverse of Prime), was PrimePi – user1339898 Aug 5 '12 at 6:05

My favorite form:

p = Prime ~Array~ PrimePi@# &;

p @ 20


share|improve this answer

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

share|improve this answer
The OP is not asking for an algorithm, but for a specific function in a specific language. Moreover, the language in question have the needed primitives already available. Please look at the tags before answering. – belisarius has settled Aug 5 '12 at 5:38

Your Answer


