4

How can I express a sum indexed by primes in Mathematica? Two examples that I am interested in are

(1) where the primes go from $p=2$ to, say, $p=17$.

(2) It would also be useful to have the sum go from $p=2$ to largest prime less than $n$. I know the latter can be estimated using the prime number theorem.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
The Substitute
  • 293
  • 1
  • 11

2 Answers2

3

Here are two possibilities using the fact that p = Prime[i] is the $i^{th}$ prime. A simple sum indexed by primes from $p=2$ to $p=17$ (the $7^{th}$ prime):

Sum[f[Prime[i]], {i, 7}]

(* f[2] + f[3] + f[5] + f[7] + f[11] + f[13] + f[17] *)

And a sum from $p = 2$ to the largest prime less than $n$:

Block[{n = 18},
 Sum[f[Prime[i]], {i, PrimePi[n]}]
]

(* f[2] + f[3] + f[5] + f[7] + f[11] + f[13] + f[17] *)

You may also find NextPrime[n, k] useful -- it finds the $k^{th}$ above $n$ (or below for negative $k$).

aardvark2012
  • 5,424
  • 1
  • 11
  • 22
2

Consider

sumOverPrimes[f_, n_Integer /; n > 1] := 
  Total @ Table[f[Prime[i]], {i, 1, PrimePi[n]}]

With this function,

sumOverPrimes[f, 18]

f[2] + f[3] + f[5] + f[7] + f[11] + f[13] + f[17]

and

1 + sumOverPrimes[#^2 + 1 &, 6]

42

m_goldberg
  • 107,779
  • 16
  • 103
  • 257