# Stop (Parallel)Table evaluation when wanted case is found

I have to go through a long list of evaluations, for which I suppose Table instead of For or While is the good way to go and actually I use ParallelTable to speed it up. But only the first one in the list satisfying a certain condition is needed. In order to save time, how to stop the evaluation once the first result is found?

I know While works. The concern is usually people suggest Table instead of For or While for speeding up.

A minimal example might be the following - trying to find the 100th prime number (count==100 as the condition). Certainly, this specific example probably has other approaches. What I need is a general recipe described above.

count = 0;
Table[count += If[PrimeQ[i], 1, 0];, {i, 1000}];

• Sounds like a job for Throw[]/Catch[]: Module[{count = 0}, Catch[Table[count += If[PrimeQ[i], 1, 0]; If[count == 100, Throw[i]], {i, 1000}]]]. – J. M.'s technical difficulties Jan 25 at 22:25
• does it have to be ParallelTable? Can you do it with ParallelSubmit? Because with ParallelSubmit, together with WaitNext, you can stop the evaluation when the first result is finished. There is a guy who has this in a video at 1h 8m 8s: youtube.com/watch?v=9yuzQKsQfZA&t=1h8m8s – Andreas Lauschke Jan 25 at 23:30
• @J.M. It doesn't work for ParallelTable? – xiaohuamao Jan 26 at 0:05
• This sounds like the kind of thing ParallelTry was designed for – Lukas Lang Jan 26 at 0:05
• @LukasLang Exactly what I need. Thanks! You can make it an answer if you like. – xiaohuamao Jan 26 at 7:40

My first idea was a classical While loop along with NextPrime:

counter = 0;
p = Prime;
While[counter < 100,
counter++;
p = NextPrime[p];
];
p


But then it occurred to me that a simple Nest would also work:

Nest[NextPrime, 2, 100]