Home > OS >  projecteuler problem 8 - unsure on what is wrong with my code
projecteuler problem 8 - unsure on what is wrong with my code

Time:07-02

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.

above is the question. when i run my code it works and runs how i expect it to, but the programme always finishes without finding an answer. any advice on how to improve my code would be appreciated.


for k in range (1,1000):
    c = 1000 - k 

    for i in range (1,c):
        b = c - i 
        c_sqr = c ** 2
        b_sqr = b ** 2 
        a = c - b 
        a_sqr = a ** 2

        if a_sqr   b_sqr == c_sqr:
            if a   b   c == 1000:
                product = a * b * c 
                print(f"{product} is the answer")
                exit()
            else:
                print("Pythagorean triplet!")
        else:
            josephmama = 11
            print("not a pythagorean triplet")

CodePudding user response:

In your code c < 1000 and a b == c are invariants. The sum (a b c) == 2 * c requires that the longest side(hypotenuse) of the right triangle to be as long as the sum of the other sides, and there's no such numbers that satisfy it and so the if body never executes.

for a in range(1, 1000):
    for b in range(1, 1000):
        c = 1000 - (a   b)
        if (a ** 2   b ** 2 == c ** 2):
            print(a * b * c)
            exit()

CodePudding user response:

a is not always equal to c - b

it just has to be less than b so consider to do a loop for a as well that is

...in range (1, b)

Also, are you sure that a, b and c will be integers?

  • Related