Skip to content
Prev 313919 / 398506 Next

Breaking out of multiple loops

Something like this?

n<-1000
pythag<-function(n){
  for(i in 3:((n-3)/3))
    for(j in (i+1):((n-i)/2))
      if(i^2+j^2==(n-i-j)^2) return(i*j*(n-i-j))
}
system.time(print(pythag(n)))

Interesting -- seems to improve speed by ~12%. Not sure if that's
because stop() has more overhead, or if functions are innately faster
somehow. Still seems like there should be a way to break out of nested
loops, though...

-b

On Tue, Dec 18, 2012 at 4:50 PM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote: