6

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]];
           A]

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?

1

3 Answers 3

7

For example

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

Usage

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

Mathematica graphics

1
  • Thanks. The part I was missing (I called it ???, basically the inverse of Prime), was PrimePi Aug 5, 2012 at 6:05
3

My favorite form:

p = Prime ~Array~ PrimePi@# &;

p @ 20

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

-1

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.

1
  • 4
    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. Aug 5, 2012 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.