## Saturday, January 14, 2012

### Project Euler Problem 9 in Scala

This is 9 in a series.  The previous post is at, Project Euler Problem 8 in Scala

I've still been (slowly) working my way through the Project Euler Problems.  The next one is problem 9 which reads:
A Pythagorean triplet is a set of three natural numbers, a  b  c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
For this problem, I didn't use anything fancy.  Two for-comprehensions and basic math produced the solution in short order.  The only thing to mention about this solution is that it actually finds the solution twice since I'm iterating1 to 998 twice. I considered trying to optimize this, however, it runs plenty fast.  Since my goal in solving these isn't to come up with the fastest solution, but to come up with a solution that has no mutable state, I have met my goal.  Therefore, I present you the solution to problem 9:

object Problem9 {
def main(args: Array[String]): Unit = {
for (a <- 1 to 998) {
for (b <- 1 to 998) {
val c = 1000 - (a + b)
if ((a * a) + (b * b) == (c * c)) {
println("the triplet is " + a + " " + b + " " + c)
println("the product is " + (a * b * c))
}
}
}
}
}

I think that's all for this one.  Problem 10 is in the hopper...