Euler 9
So the other night I was a bit bored and decided to do something to pass the time. I first came across Project Euler a while ago, but had never gone further than problem #1. Boredom is a great motivator and I went through problems #2 thru #9 last night and I decided to post my solutions in search of better ones. Feel free to comment with your suggestions.
Project Euler’s Problem #9 statement is —
A Pythagorean triplet is a set of three natural numbers, , for which:
For example, .
There exists exactly one Pythagorean triplet for which .
Find the product .
Using removes one variable immediately. Substituting that into and solving for gives
That leaves only the possible values of a to search:
total = 1000
for a in range(1, total // 3):
numerator = total * (total - 2 * a)
denominator = 2 * (total - a)
if numerator % denominator:
continue
b = numerator // denominator
c = total - a - b
if a < b < c:
print(a * b * c)
break
The divisibility check ensures that b is a natural number. The triplet is
, so the program prints 31875000 in linear time and constant
space.