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

后端 未结 6 495
星月不相逢
星月不相逢 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:09

    Here's another couple of alternatives using NextPrime:

    pairs1[pmax_] := Select[Range[pmax], PrimeQ[#] && NextPrime[#] == 2 + # &]
    
    pairs2[pnum_] := Module[{p}, NestList[(p = NextPrime[#];
                          While[p + 2 != (p = NextPrime[p])]; 
                          p - 2) &, 3, pnum]] 
    

    and a modification of your Reap/Sow solution that lets you specify the maximum prime:

    pairs3[pmax_] := Module[{k,p},
                       Reap[For[k = 1, (p = Prime[k]) <= pmax, k++,
                            If[PrimeQ[p + 2], Sow[p]]]][[-1, 1]]]
    

    The above are in order of increasing speed.

    In[4]:= pairs2[10000]//Last//Timing
    Out[4]= {3.48,1261079}
    In[5]:= pairs1[1261079]//Last//Timing
    Out[5]= {6.84,1261079}
    In[6]:= pairs3[1261079]//Last//Timing
    Out[7]= {0.58,1261079}
    

提交回复
热议问题