I want to write an algorithm that returns a sequence of numbers, starting from a specified point but stopping once a criterion has been reached. For example nonPrimeSequence[x_] would return the sequence of numbers, stopping when the next number in the line is not prime anymore. E.g.:

In[1]:= nonPrimeSequence[24]
Out[1]= {24,25,26,27,28}

since all numbers from 24 up to and including 28 are not prime, but 29 is.

My question is how do I create a function that can apply an If[] function repeatedly to successive arguments in a list or range whilst keeping track of where in a sequence it is up to, like the i in Table[i, {i,10}]

I know that for this example something like PrimeQ would probably do the trick, but I'm looking for a general way to check for a criterion fulfillment.

As far as I understand, NestWhileList[] would't do the trick, seeing as it doesn't have a way to keep track of the iterator.

  • $\begingroup$ Many ways to do this, but you're on track for one of them with your 'NestWhileList` - just decorate your result with an incremented counter... $\endgroup$
    – ciao
    Commented Apr 11, 2014 at 20:10

1 Answer 1


What's wrong with

nonPrimeSequence[x_] := NestWhileList[# + 1 &, x, Not[PrimeQ[# + 1]] &]

(* {24, 25, 26, 27, 28} *)



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