简体   繁体   中英

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

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

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

a is not always equal to c - b

by deriving b from c and a from c and b you are unnecessarily limiting the options of what b and a could be. Just loop through all combinations of a, b and c, add the constrains you have and you'll eventually get your triplet.

for a in range(1, 1000):
    for b in range(1, 1000):
        for c in range(1, 1000):
            if a+b+c == 1000:
                if a**2+b**2 == c**2:
                    if a < b:
                        if b < c:
                            print(f"My Triplet: a: {a}, b: {b}, c:{c}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM