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

后端 未结 6 500
星月不相逢
星月不相逢 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 20:55

    Yes, this is another answer. Another alternative that includes the flavour of the Reap/Sow approach and the FoldList approach would be to use Scan.

    result = {1};
    Scan[With[{p=Prime[#]},If[PrimeQ[p+2],result={result,p}]]&,Range[2,K] ];
    Flatten[result]
    

    Again, this involves a long list of integers, but the intermediate Prime results are not stored because they are in the local scope of With. Because p is a constant in the scope of the With function, you can use With rather than Module, and gain a bit of speed.

提交回复
热议问题