# Counting zeros of list from Twin Primes calculation

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}

• May not be an elegant solution but here is one way If[MemberQ[#, 0], Length@#, Nothing] & /@ Split@alst Jun 19, 2021 at 2:50
• not sure how fast it is, but check out: Length /@ SequenceSplit[alst, {{_, _}}] Jun 19, 2021 at 3:01
• DeleteCases[Count[#, 0] & /@ Split@alst, 0] Jun 19, 2021 at 3:02
• similar to my other one, but a bit different: Length /@ SequenceCases[alst, {0 ..}] Jun 19, 2021 at 3:19
• 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]] Jun 19, 2021 at 3:39

Using Split and Cases:

Cases[Split@alst, a:{0..} :> Length@a]
(* {1,1,1,2,2,3,2,5,1,4,1,5} *)

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} *)
`