4
$\begingroup$

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.

$\endgroup$
0

2 Answers 2

3
$\begingroup$

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$).

$\endgroup$
2
$\begingroup$

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

$\endgroup$

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