Welcome back F# junkies! In this installment of YAPES1, we’re tackling Project Euler problem nine.
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
Like we’ve done before, we’ll break this problem down into steps:
Sound good?
The first order of business is to determine how to generate Pythagorean triples. It turns out that there are many ways to do this. However, to keep it simple, we will use Euclid’s classic formula:
Given a pair of positive integers m and n with m > n a = 2mn, b = m2 – n2, c = m2 + n2
Truthfully, this formula doesn’t actually produce every possible Pythagorean triple. However, since the solution is within the set that it generates, that really isn’t a problem.
a = 2kmn, b = k(m2 – n2), c = k(m2 + n2)
First, we’ll declare an F# function that calculates a Pythagorean triple using Euclid’s formula.
Using the above function, it’s easy to produce a stream of Pythagorean triples. Our strategy will be to start with the pair, m = 2 and n = 1. To generate the next pair, we’ll first check if n + 1 is less than m. If it is, we’ll use m and n + 1 as the next pair, otherwise we’ll use m + 1 and 1. Using Seq.unfold, we can use this algorithm to produce an infinite stream of Pythagorean triples:
With our generator in place, we can easily solve the problem.
While the above solution works well, we can abstract further to produce a more elegant solution. First, we’ll declare three functions to handle the three operations that we’re performing explicitly, sum, product and equals.
Now, we can restate our solution using these functions with a bit of function composition to produce a truly beautiful solution.
As we’ve seen once before, function composition is beautiful.
1Yet Another Project Euler Series
Page rendered at Tuesday, February 07, 2012 5:38:23 AM (Pacific Standard Time, UTC-08:00)
If feel a bit behind and need to catch up on WPF, this is the book.
Great book on F# containing from Beginner to Advanced. It even has chapters on more arcane features of the language, such as Computation Expressions and Quotations.
Because this book provides source code in Standard ML, it's a fantastic resource for learning F#. One bit of warning: this book does not teach classic data structures. While structures such as binomial heaps and red-black trees are presented, it is assumed that the reader already knows and understands them.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.