is there a way to optimise an algorithm that finds the pythagorean triplet for which a+b+c=1000?

73 Views Asked by At

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)
1

There are 1 best solutions below

1
On

An easy optimization would be to avoid doing unnecassary operations.

First of all, why test all a in range(3,b) when you know that a valid solution should fulfill the condition a+b+c ==1000

The first optimization would be :

 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) :
        a = 1000 - b - c
        if a >= 0:
            if isPythagoeranTriplet(a,b,c):
                print(a*b*c)

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:

 from math import pow

 def isPythagoeranTriplet(a,b,c):
     return pow(a,2)+pow(b,2) == pow(c,2)

for c in range(5,1000) :
    for b in range(4,c) :
        a = 1000 - b - c
        if a >= 0 and a < b:
            if isPythagoeranTriplet(a,b,c):
                print(a*b*c)

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, if c=6, b=5, you cannot have a a smaller than both values and fulfilling the condition a+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.