View Category

### Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

`[3, 4, 5]`

`[6, 8, 10]`

`[5, 12, 13]`

`[9, 12, 15]`

`[8, 15, 17]`

`[12, 16, 20]`

`[15, 20, 25]`

haskell

import Data.List

import Control.Monad

pythTriangles :: [(Int,Int,Int)]

pythTriangles = do

a <- [1..20]

b <- [a+1..20]

c <- [1..2*b]

guard (a*a + b*b == c*c)

return (a,b,c)

cmpThird (_,_,a) (_,_,b)

| a < b = LT

| a == b = EQ

| otherwise = GT

main = mapM_ print (sortBy cmpThird pythTriangles)

import Control.Monad

pythTriangles :: [(Int,Int,Int)]

pythTriangles = do

a <- [1..20]

b <- [a+1..20]

c <- [1..2*b]

guard (a*a + b*b == c*c)

return (a,b,c)

cmpThird (_,_,a) (_,_,b)

| a < b = LT

| a == b = EQ

| otherwise = GT

main = mapM_ print (sortBy cmpThird pythTriangles)

import Data.Function

import Data.List

pythTriangles =

[(a,b,c) | a <- [1..20], b <- [a+1..20], c <- [1..2*b], a*a + b*b == c*c]

main = mapM_ print $ sortBy (compare `on` third) pythTriangles where

third (_,_,x) = x

import Data.List

pythTriangles =

[(a,b,c) | a <- [1..20], b <- [a+1..20], c <- [1..2*b], a*a + b*b == c*c]

main = mapM_ print $ sortBy (compare `on` third) pythTriangles where

third (_,_,x) = x

### Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

haskell

8 `gcd` 12