If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p ≤ 1000, is the number of solutions maximised?


In [10]:
let square x = x * x

// writing this out long-form, probably faster?
let sortTriple (a,b,c) =
    if a >= b then
        if b >= c then (a,b,c) else (a,c,b)
    elif b >= a then
        if a >= c then (b,a,c) else (b,c,a)
    else
        if a >= b then (c,a,b) else (c,b,a)

let pairWith lst x = 
    lst |> List.map (fun y -> (x,y)) 

// assumes sorted in descending order
let isRightTriangle (a,b,c) = 
    (square a) = (square b) + (square c) 

let solutionsFor p =
    [1..(p-1)]
    |> List.map (fun a -> pairWith [1..(a-1)] a)
    |> List.concat
    |> List.filter (fun (a,b) -> (p-a-b) > 0)
    |> List.map (fun (a,b) -> sortTriple (a,b,p-a-b))        
    |> List.filter isRightTriangle
    |> List.distinct
    |> List.length 

[5..1000]
|> List.map (fun p -> (p, (solutionsFor p)))
|> List.sortBy (fun (p, solns) -> -solns)
|> List.head
|> fst

//solutionsFor 120


Out[10]:
840