[R] Breaking out of multiple loops

McCloskey, Bryan bmccloskey at usgs.gov
Tue Dec 18 19:02:37 CET 2012


Hey all,

I'm currently working through the problems at Project Euler -- this
question came up while working on Problem 9
(http://projecteuler.net/problem=9):

"A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which, a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 9 + 16 = 25 =
5^2. There exists exactly one Pythagorean triplet for which a + b + c
= 1000. Find the product abc."

Not too hard:

n=1000
for(i in 1:floor(n/3))
  for(j in (i+1):floor(n/2-i/2))
    if(i^2+j^2==(n-i-j)^2) {print(i*j*(n-i-j)); stop()}

I could just let the for loops finish looping after it finds the
answer, and it would still run in under a second, but the goal of
Project Euler is sort of to see how efficiently (and quickly) you can
solve these problems, so in that spirit I would like to break out of
the for loops early once the answer is found -- hence the call to
stop(). However, this seems "improper", as it throws up an error. Is
there a way to exit out of both for loops with a call to "break" or
similar that would not throw errors (or is it fine the way I've coded
it)? (I realize I could put an "if(i^2+j^2==(n-i-j)^2) break"
statement in the outer loop, but again that's inefficient, as it's
checking that conditional hundreds of times.)

So is there a way to "cleanly" break out of multiple loops?

Thanks,
-bryan



More information about the R-help mailing list