i'm trying to solve project euler's 9th problem , and this code does the job but it takes too long to do so (note : i just realized that the a<b<c condition is useless in the function since it's always the case in the loop)
from math import pow
def isPythagoeranTriplet(a,b,c):
return a < b < c and pow(a,2)+pow(b,2) == pow(c,2)
for c in range(5,1000) :
for b in range(4,c) :
for a in range(3,b) :
if isPythagoeranTriplet(a,b,c) and a+b+c == 1000:
print(a*b*c)
An easy optimization would be to avoid doing unnecassary operations.
First of all, why test all
a
inrange(3,b)
when you know that a valid solution should fulfill the conditiona+b+c ==1000
The first optimization would be :
You could also change your function so the check is easier assuming that
a<b<c
and check only for number that already satisfy this condition:By construction, you have
b<c
. You could also still optimize it to test a smaller amount of b and c values. As you can see, ifc=6, b=5
, you cannot have aa
smaller than both values and fulfilling the conditiona+b+c = 1000
. Most of the optimization you can actually do are on the ranges of loops, to discard before hand values that don't need to be tested.