Project Euler – Problem 39 Solution

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

The real-time data platform that empowers developers to build innovative products faster and more reliably than ever before.

Learn more

Problem

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?

Solution

// define function to find the number of solutions for p
let countSolutions p =
    [4*p/10..6*p/10]
    |> List.filter (fun c ->
        [1..p]
        |> Seq.takeWhile (fun b -> b + c < p)
        |> Seq.exists (fun b -> (pown (p-b-c) 2 + pown b 2) = pown c 2))
    |> List.length

let answer = [1..1000] |> List.maxBy countSolutions

Whenever you’re ready, here are 4 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

1 thought on “Project Euler – Problem 39 Solution”

  1. I have to remind myself that sometimes it’s better to work backwards. As usual, your solution is better than mine :) You started with possible Cs and generated possible As and Bs from that, whereas I started with As and Bs, computed C, and filtered any combination thereof that didn’t look “right” (get it? it’s a triangle joke! I kill me).

    At one point, I must have known that the hypotenuse is between 0.4p and 0.6p, but apparently I’ve forgotten that in the 30 years since I learned it.

Leave a Comment

Your email address will not be published. Required fields are marked *