# Generating Pythagorean triples in Scala

**URL:** <https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833>\
**Category:** Question\
**Created:** [December 31, 2018, 5:36pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833 "2018-12-31T17:36:21Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![yawaramin](https://users.scala-lang.org/user_avatar/users.scala-lang.org/yawaramin/32/224_2.png) [@yawaramin](https://users.scala-lang.org/u/yawaramin)\
**Post date:** [December 31, 2018, 5:36pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/1 "2018-12-31T17:36:22Z")

</div>

Nowadays there is something of a ‘challenge’ going around in performant programming language circles about whether they can implement an easy-to-read Pythagorean triple generator using (infinite) ranges. E.g., see [https://atilanevesoncode.wordpress.com/2018/12/31/comparing-pythagorean-triples-in-c-d-and-rust/](https://atilanevesoncode.wordpress.com/2018/12/31/comparing-pythagorean-triples-in-c-d-and-rust/) . I found this coincidentally amusing because I recently submitted a PR to the Scala documentation site that uses the Pythagorean triple generation as an example to show the power and elegance of for-comprehensions: [https://github.com/scala/docs.scala-lang/pull/1235](https://github.com/scala/docs.scala-lang/pull/1235)

So naturally I tried converting my example to use an infinite range (concretely, an `Iterator`):

```auto
def naturals = Iterator.from(1)

def pythagoreanTriples = for {
  a <- naturals
  b <- naturals if b > a
  c <- naturals if a * a + b * b == c * c
} yield (a, b, c)

pythagoreanTriples take 2 foreach println

```

However, this generator seems to get stuck indefinitely. I tried to rewrite it with slightly more precise functions:

```auto
def naturals = Iterator.from(1)

def pythagoreanTriples = naturals.flatMap { a =>
  naturals.dropWhile(a.>=).flatMap { b =>
    naturals.collect {
      case c if c * c == a * a + b * b => (a, b, c)
    }
  }
}

pythagoreanTriples take 2 foreach println

```

However, this generator suffers the same problem–stuck indefinitely.

Can anyone shed light on why the iterators are seemingly not iterating?

---

<div class="post-metadata">

**Author:** ![siddhartha-gadgil](https://users.scala-lang.org/user_avatar/users.scala-lang.org/siddhartha-gadgil/32/46_2.png) [@siddhartha-gadgil](https://users.scala-lang.org/u/siddhartha-gadgil)\
**Post date:** [January 1, 2019, 3:23am UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/2 "2019-01-01T03:23:44Z")

</div>

If you use the same iterator, if a value (say `1`) is used for `a` I don’t think it will be used for `b`. As far as I can see, there are two ways around this.

- Use three different iterators, with the same definition
- Use a stream

regards,  
Siddhartha

---

<div class="post-metadata">

**Author:** ![yawaramin](https://users.scala-lang.org/user_avatar/users.scala-lang.org/yawaramin/32/224_2.png) [@yawaramin](https://users.scala-lang.org/u/yawaramin)\
**Post date:** [January 1, 2019, 5:39pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/3 "2019-01-01T17:39:57Z")

</div>

Thank you. I believe I am using three different iterators at runtime (they are generated by the `naturals` method calls). I’ll keep investigating further as to where the freeze is happening.

---

<div class="post-metadata">

**Author:** ![curoli](https://users.scala-lang.org/user_avatar/users.scala-lang.org/curoli/32/1753_2.png) [@curoli](https://users.scala-lang.org/u/curoli)\
**Post date:** [January 1, 2019, 9:24pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/4 "2019-01-01T21:24:02Z")

</div>

Your code loops over Ints indefinitely for c, while a=1 and b=1, so it is not finding any triples.

---

<div class="post-metadata">

**Author:** ![curoli](https://users.scala-lang.org/user_avatar/users.scala-lang.org/curoli/32/1753_2.png) [@curoli](https://users.scala-lang.org/u/curoli)\
**Post date:** [January 2, 2019, 3:53pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/6 "2019-01-02T15:53:48Z")

</div>

I’m not sure what you mean by short-circuiting traversal and how it will fix this. Perhaps you want to stop iterating after the first hit? You could call the find method for that. But it won’t help if for a given a and b there is no solution for c.

You should have only one indefinite iterator, and it should be the outer-most loop (i.e. the first argument in for). You could have an indefinite iterator for c and use 1 \< a \< b \< c to have finite ranges for a and b.

But since you speak of performance: iterating over all three variables and filtering is, of course, extremely inefficient. It is much faster to iterate over two of them and calculate the third.

---

<div class="post-metadata">

**Author:** ![martijnhoekstra](https://users.scala-lang.org/user_avatar/users.scala-lang.org/martijnhoekstra/32/424_2.png) [@martijnhoekstra](https://users.scala-lang.org/u/martijnhoekstra)\
**Post date:** [January 3, 2019, 8:41am UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/7 "2019-01-03T08:41:55Z")

</div>

The main issue here is that `Iterator.from(1)` is infinite, and wraps around overflow. This is in agreement with the scaladoc, but also pretty surprising behaviour to me.

That means that `Iterator.from(1).filter(_ => false).next()` will loop forever.

A non-looping version, `def positiveInts = Iterator.from(1).takeWhile(i => i + 1 > 0)` should terminate. Though I can’t check atm, since I’m on my phone.

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [January 3, 2019, 11:11am UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/8 "2019-01-03T11:11:35Z")

</div>

> [@martijnhoekstra](#):
>
> `Iterator.from(1).takeWhile(i => i + 1 > 0)` should terminate.

It terminates, but you will find `(1,4,869476073)`.

```auto
scala> 1 * 1 + 4 * 4
res2: Int = 17

scala> 869476073 * 869476073
res3: Int = 17

```

`def naturals = Iterator.from(1).takeWhile(i => i * i / i == i)` would work, but still take a looong time. And I guess the challenge is to implement an algorithm that can work for unbounded numbers like `BigInt`.

---

<div class="post-metadata">

**Author:** ![charpov](https://users.scala-lang.org/user_avatar/users.scala-lang.org/charpov/32/500_2.png) [@charpov](https://users.scala-lang.org/u/charpov)\
**Post date:** [January 3, 2019, 2:16pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/9 "2019-01-03T14:16:19Z")

</div>

What is the goal exactly? What’s wrong with:

```auto
val p = for {
  b <- Iterator.from(1)
  a <- 1 until b
} yield (a, b, a * a + b * b)

```

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [January 3, 2019, 2:31pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/10 "2019-01-03T14:31:57Z")

</div>

> [@charpov](#):
>
> What is the goal exactly? What’s wrong with:
> 
> ```auto
> val p = for {
> b <- Iterator.from(1)
> a <- 1 until b
> } yield (a, b, a * a + b * b)
> 
> ```

We’re looking for a `c` equal to `math.sqrt(a * a + b * b)` where `c` is an integer. So the following would be a relatively efficient implementation, disregarding integer overflow:

```auto
def pythagoreanTriples = (for {
  b <- Iterator.from(1)
  a <- 1 until b
  c2 = a * a + b * b
} yield (a, b, math.sqrt(c2).toInt, c2)).collect{ case (a,b,c,c2) if c*c == c2 => (a, b, c) }

```

---

<div class="post-metadata">

**Author:** ![charpov](https://users.scala-lang.org/user_avatar/users.scala-lang.org/charpov/32/500_2.png) [@charpov](https://users.scala-lang.org/u/charpov)\
**Post date:** [January 3, 2019, 2:39pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/11 "2019-01-03T14:39:56Z")

</div>

Got you. I forgot what Pythagorean triples were. Could also be written as:

```auto
val p = for {
  b <- Iterator.from(1)
  a <- 1 until b
  c2 = a * a + b * b
  c = Math.sqrt(c2).toInt
  if c * c == c2
} yield (a, b, c)

```

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [January 3, 2019, 2:41pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/12 "2019-01-03T14:41:25Z")

</div>

> [@charpov](#):
>
> Could also be written as:
> 
> ```auto
> val p = for {
> b <- Iterator.from(1)
> a <- 1 until b
> c2 = a * a + b * b
> c = Math.sqrt(c2).toInt
> if c * c == c2
> } yield (a, b, c)
> 
> ```

Yes indeed 😅 I was just about to edit my post.

---

<div class="post-metadata">

**Author:** ![martijnhoekstra](https://users.scala-lang.org/user_avatar/users.scala-lang.org/martijnhoekstra/32/424_2.png) [@martijnhoekstra](https://users.scala-lang.org/u/martijnhoekstra)\
**Post date:** [January 3, 2019, 3:57pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/13 "2019-01-03T15:57:48Z")

</div>

Sure, I intended to answer OPs bafflement though, not do their exercises for them.

---

<div class="post-metadata">

**Author:** ![yawaramin](https://users.scala-lang.org/user_avatar/users.scala-lang.org/yawaramin/32/224_2.png) [@yawaramin](https://users.scala-lang.org/u/yawaramin)\
**Post date:** [January 5, 2019, 3:10am UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/14 "2019-01-05T03:10:26Z")

</div>

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:

```auto
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 🙂 I just want to avoid ‘accidentally quadratic’, which your hint achieved!

```auto
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.

---

<div class="post-metadata">

**Author:** ![charpov](https://users.scala-lang.org/user_avatar/users.scala-lang.org/charpov/32/500_2.png) [@charpov](https://users.scala-lang.org/u/charpov)\
**Post date:** [January 5, 2019, 2:43pm UTC](https://users.scala-lang.org/t/generating-pythagorean-triples-in-scala/3833/15 "2019-01-05T14:43:07Z")

</div>

Yes, that’s the way. The beauty of Scala is that this is much more readable than the equivalent:

```auto
def pythagoreanTriples =
  Iterator.from(1).flatMap { c =>
  (1 until c).flatMap { b =>
    (1 until b).withFilter(a => c * c == a * a + b * b).map(a => (a, b, c))
  }
}

```
