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}];
  • 1
    $\begingroup$ 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}]]]. $\endgroup$ – J. M.'s technical difficulties Jan 25 at 22:25
  • 3
    $\begingroup$ 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 $\endgroup$ – Andreas Lauschke Jan 25 at 23:30
  • $\begingroup$ @J.M. It doesn't work for ParallelTable? $\endgroup$ – xiaohuamao Jan 26 at 0:05
  • 3
    $\begingroup$ This sounds like the kind of thing ParallelTry was designed for $\endgroup$ – Lukas Lang Jan 26 at 0:05
  • $\begingroup$ @LukasLang Exactly what I need. Thanks! You can make it an answer if you like. $\endgroup$ – xiaohuamao Jan 26 at 7:40

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

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

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

Nest[NextPrime, 2, 100]
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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