I'd like to evaluate


over the $k$ largest previous primes $p\le n/2$, where $n$ is the parameter. E.g., if $n=20$ and $k=3$, I'd like the product to be over the 3 previous primes less than or equal to $20/2=10$: namely, $7,5,3$.

The code for the previous prime is

PreviousPrime[n_Integer] := Block[{i = n}, While[! PrimeQ[-i]]; i]
SetAttributes[PreviousPrime, Listable];

How can I take a product over $k$ previous primes?


2 Answers 2


You can use NextPrime to find previous primes too, so you don't need your PreviousPrime function.

To get your product, you can use

primeprod[n_, k_] := Product[1 - 1/i, {i, NextPrime[n/2, Range[-k, -1]]}]


primeprod[20, 3]

(* 16/35 *)

You can also generalise it by adding the product function as an argument:

primeprod2[n_, k_, f_] := Product[f[i], {i, NextPrime[n/2, Range[-k, -1]]}]

In which case

primeprod2[20, 3, 1 - 1/# &]

(* 16/35 *)

One can of course use PrimePi[] + Prime[] instead:

primeprod[n_, k_, f_] :=
With[{p = PrimePi[n/2]}, Apply[Times, f[Prime[Range[p - k + 1, p]]]]]

primeprod[20, 3, 1 - 1/# &]

Your Answer

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

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