5
$\begingroup$
twinPs[n_] = If[(Prime[n + 1] - Prime[n]) == 2, {Prime[n], Prime[n + 1]}, 0]
alst = Table[twinPs[x], {x, 41}]

{0, {3, 5}, {5, 7}, 0, {11, 13}, 0, {17, 19}, 0, 0, {29, 31}, 0, 0, \
{41, 43}, 0, 0, 0, {59, 61}, 0, 0, {71, 73}, 0, 0, 0, 0, 0, {101, 103}, \
0, {107, 109}, 0, 0, 0, 0, {137, 139}, 0, {149, 151}, 0, 0, 0, 0, 0, \ 
{179, 181}}

How to make a count zeros list. ie. Return the length of a gap between successive pairs of twin primes?

answer = {1,1,1,2,2,3,2,5,1,4,1,5}
$\endgroup$
8
  • 1
    $\begingroup$ May not be an elegant solution but here is one way If[MemberQ[#, 0], Length@#, Nothing] & /@ Split@alst $\endgroup$ Jun 19, 2021 at 2:50
  • 1
    $\begingroup$ not sure how fast it is, but check out: Length /@ SequenceSplit[alst, {{_, _}}] $\endgroup$
    – thorimur
    Jun 19, 2021 at 3:01
  • 1
    $\begingroup$ DeleteCases[Count[#, 0] & /@ Split@alst, 0] $\endgroup$ Jun 19, 2021 at 3:02
  • 1
    $\begingroup$ similar to my other one, but a bit different: Length /@ SequenceCases[alst, {0 ..}] $\endgroup$
    – thorimur
    Jun 19, 2021 at 3:19
  • 1
    $\begingroup$ and another one just for fun :) this one also counts length 0 runs of zeros, i.e. when two twin prime pairs are consecutive Flatten[(Composition @@ Replace[alst, {0 -> (# + {1, 0} &), {_, _} -> ({0, #} &)}, 1])[0]] $\endgroup$
    – thorimur
    Jun 19, 2021 at 3:39

2 Answers 2

5
$\begingroup$

Using Split and Cases:

Cases[Split@alst, a:{0..} :> Length@a]
(* {1,1,1,2,2,3,2,5,1,4,1,5} *)
$\endgroup$
4
$\begingroup$
Clear["Global`*"]

twinPs[n_] = 
  If[(Prime[n + 1] - Prime[n]) == 2, {Prime[n], Prime[n + 1]}, 0];
alst = Table[twinPs[x], {x, 41}];

answer = SequenceCases[alst, {p : Repeated[0]} :> Length[{p}]]

(* {1, 1, 1, 2, 2, 3, 2, 5, 1, 4, 1, 5} *)
$\endgroup$

Your Answer

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

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