Message Boards Message Boards

0
|
3552 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Extract elements of a list meeting a specific condition.

Posted 3 years ago

I'm trying to make a list of numbers that are twin primes. I wrote a function to check if a number is a twin prime or not.

Attributes[twinPrimeQ] = {Listable};

twinPrimeQ[n_] := 
 PrimeQ[n] && 
  n > 2 && (NextPrime[n] - n == 2  || n - NextPrime[n, -1] == 2)

How can I apply that to a list of integers, to pick out the twin primes, which will hopefully be those at https://oeis.org/A001097 ?

I thought something like this would work

In[19]:= Table[n, {n, 0, 20}]  /; twinPrimeQ[n]

Out[19]= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
  17, 18, 19, 20} /; twinPrimeQ[n]

but it obviously does not work as I intended.

POSTED BY: David Kirkby
3 Replies
Posted 3 years ago

Thank you for your help.

Dave

POSTED BY: David Kirkby
Posted 3 years ago

This is about 3x faster

twinPrime2Q[n_] := PrimeQ[n] && (PrimeQ[n + 2] || PrimeQ[n - 2])

<< GeneralUtilities`
BenchmarkPlot[{twinPrimeQ, twinPrime2Q}, Range[#] &, 10^Range[6], "IncludeFits" -> True]

enter image description here

POSTED BY: Rohit Namjoshi
Posted 3 years ago

Hi David,

One way

Table[n, {n, 0, 20}] // Select[twinPrimeQ]

Listable allows this

Table[n, {n, 0, 20}] // twinPrimeQ
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract