project euler #9
Friday, September 5th, 2008Many of you know I’ve been sucked into the world of Project Euler. I love problem-solving with computers, and I love math, despite not being great at problem-solving with computers and being even worse at mathematics.
As of yet, most of my solutions have been brute-force attempts which get the answer quite ahem thoroughly, if not the most efficiently.
Well, project euler #9 involves calculating pythagorean triplets, and I’d left it for a while deciding it would involve a pain-in-the-ass buttload of calculating and would take about 20 minutes to run. However, I’ve been listening to The Teaching Company’s The Joy of Thinking, and they presented ways of calculating the pythagorean triplets that I’d never really thought of.
Anyways, this morning I was waiting around for a while between errands, and a napkin and 4 lines of python inspired me. All I had to do was reduce the fact that:
2mn+(m*m - n*n)+(m*m+n*n) = 1000
to
m(m+n)=500 and run through m and n with n < m. BAM!
[nate@pepper python]$ time ./peuler9.py
sum = 1000
product = *****
real 0m0.012s
user 0m0.010s
sys 0m0.000s
Yes, I removed the actual answer so as not to be a spoiler. However, I will include my full source code, as I’m amazed at how simple it was, and maybe you’ll enjoy it too.
(source code after the jump…)
(more…)