Generate a list in Mathematica with a conditional tested for each element

后端 未结 6 492
星月不相逢
星月不相逢 2020-12-28 20:44

Suppose we want to generate a list of primes p for which p + 2 is also prime.

A quick solution is to generate a complete list of the first n

6条回答
  •  旧巷少年郎
    2020-12-28 21:06

    You can perhaps try something like this:

    Clear[f, primesList]
    f = With[{p = Prime[#]},Piecewise[{{p, PrimeQ[p + 2]}}, {}] ] &;
    primesList[k_] := Union@Flatten@(f /@ Range[k]);
    

    If you want both the prime p and the prime p+2, then the solution is

    Clear[f, primesList]
    f = With[{p = Prime[#]},Piecewise[{{p, PrimeQ[p + 2]}}, {}] ] &;
    primesList[k_] := 
      Module[{primes = f /@ Range[k]}, 
       Union@Flatten@{primes, primes + 2}];
    

提交回复
热议问题