简体   繁体   English

projecteuler 问题 8 - 不确定我的代码有什么问题

[英]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 < b < c,其中,

 a^2 + b^2 = c^2

For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.例如, 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 .恰好存在一个 a + b + c = 1000 的毕达哥拉斯三元组。求积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.在您的代码中c < 1000a + b == c是不变量。 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. sum (a + b + c) == 2 * c要求直角三角形的最长边(斜边)与其他边的总和一样长,并且没有这样的数字可以满足它,所以if身体从不执行。

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 a 并不总是等于 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.通过从 c 和 a 从 c 和 b 导出 b,您不必要地限制了 b 和 a 的选项。 Just loop through all combinations of a, b and c, add the constrains you have and you'll eventually get your triplet.只需遍历 a、b 和 c 的所有组合,添加您拥有的约束,您最终会得到您的三元组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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