Write a list comprehension that finds all the Pythagorean triples for right triangles with sides shorter than 100

Write a list comprehension that finds all the Pythagorean triples for right triangles with sides shorter than 100. A Pythagorean triple is three integers a, b, and c, where a² + b² = c².

In Elixir it takes a line of code with pattern-matching to produce this.

Note the 3 patterns below, nested loops, scary I know. But at least rather than starting from 1 each time, we loop through 1 more than the last value of the outer loop.

  • a<-1..99,
  • b<-(a+1)..99,
  • c<-(b+1)..99

And the final pattern which make it all work like magic:

a*a + b*b == c*c

File: pythag.exs

for a<-1..99, b<-(a+1)..99, c<-(b+1)..99, a*a + b*b == c*c, do: IO.puts "#{a}² + #{b}² = #{c}²"

Output: console

> elixir pythag.exs
3² + 4² = 5²
5² + 12² = 13²
6² + 8² = 10²
7² + 24² = 25²
8² + 15² = 17²
9² + 12² = 15²
9² + 40² = 41²
10² + 24² = 26²
11² + 60² = 61²
12² + 16² = 20²
12² + 35² = 37²
13² + 84² = 85²
14² + 48² = 50²
15² + 20² = 25²
15² + 36² = 39²
16² + 30² = 34²
16² + 63² = 65²
18² + 24² = 30²
18² + 80² = 82²
20² + 21² = 29²
20² + 48² = 52²
21² + 28² = 35²
21² + 72² = 75²
24² + 32² = 40²
24² + 45² = 51²
24² + 70² = 74²
25² + 60² = 65²
27² + 36² = 45²
28² + 45² = 53²
30² + 40² = 50²
30² + 72² = 78²
32² + 60² = 68²
33² + 44² = 55²
33² + 56² = 65²
35² + 84² = 91²
36² + 48² = 60²
36² + 77² = 85²
39² + 52² = 65²
39² + 80² = 89²
40² + 42² = 58²
40² + 75² = 85²
42² + 56² = 70²
45² + 60² = 75²
48² + 55² = 73²
48² + 64² = 80²
51² + 68² = 85²
54² + 72² = 90²
57² + 76² = 95²
60² + 63² = 87²
65² + 72² = 97²

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com
%d bloggers like this: