Generating Pythagorean triples in Scala

Thank you! The main breakthrough for me was your suggestion that there should be only one infinite iteration. And also @charpov 's example, but I felt that I could avoid the square root calculation. This works nicely:

def pythagoreanTriples = for {
  c <- Iterator.from(1)
  b <- 1 until c
  a <- 1 until b if c * c == a * a + b * b
} yield (a, b, c)

Just to clarify, I spoke about ‘performant programming language circles’ but I’m not necessarily looking to performance tune myself :slight_smile: I just want to avoid ‘accidentally quadratic’, which your hint achieved!

scala> pythagoreanTriples take 3 foreach println
(3,4,5)
(6,8,10)
(5,12,13)

Edit: I’d also like to say I achieved my original goal, which was to demonstrate (even if just to myself) that Scala’s expressive power is light-years ahead of several other languages even if they are more performant, etc.

1 Like