Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成所有Euler砖_Python_Python 3.x - Fatal编程技术网

Python 生成所有Euler砖

Python 生成所有Euler砖,python,python-3.x,Python,Python 3.x,我最近一直在研究毕达哥拉斯的三元组,想知道生成所有三元组的最佳方法是什么 我从更广泛的阅读中了解到,有10个c

我最近一直在研究毕达哥拉斯的三元组,想知道生成所有三元组的最佳方法是什么

我从更广泛的阅读中了解到,有10个c<1000,我已经编写了一个蛮力代码来查找它们,但是速度非常慢。我只能找到Saunderson参数化,它不能生成所有的参数。所以我不确定是否有更快的方法。这是迄今为止我所拥有的代码

def isint(n):
     if n % 1 == 0:
         return True
     else:
         return False


def eulerbrick(n):
     euler_list = []
     for a in range(1,n):
         for b in range(a + 1,n):
             for c in range(b + 1,n):
                 ab = sqrt(a*a + b*b)
                 ac = sqrt(a*a + c*c)
                 bc = sqrt(b*b + c*c)

             if c > n:
                break

             if isint(ab) and isint(ac) and isint(bc):
                euler = [a,b,c]
                euler_list.append(euler)
return euler_list

谢谢你的帮助

我想,根据维基百科的说法,如果你想全部

Euler至少找到了问题的两个参数解,但都没有给出所有解

但是,您已经说过,您已经编写了一个暴力代码来查找它们,这太慢了。我想这是因为

ab = sqrt(a*a + b*b)
ac = sqrt(a*a + c*c)
bc = sqrt(b*b + c*c)
对于每一行,你要计算两个平方数和平方根——听起来不算多,但最后,这将是一个总结

如果在每个循环段的开头立即计算平方数并将其值存储在新变量中,则可以优化代码。此外,您应该尽快检查您已经计算的数字是否符合Euler砖的要求。因为如果他们不这样做,你就不必计算其他数字,也可以节省时间

最后,你会得到这样的结果:

import math
i = 1
j = 1000
for a in range(i, j):
    a_squared = a**2
    for b in range(a, j):
        b_squared = b**2
        d = math.sqrt(a_squared + b_squared)
        if not d.is_integer():
            continue
        for c in range(b, j):
            c_squared = c**2
            e = math.sqrt(a_squared + c_squared)
            if not e.is_integer():
                continue
            f = math.sqrt(b_squared + c_squared)
            if not f.is_integer():
                continue
            print("a={} b={} c={}".format(a, b, c))
不需要很长时间就能打印出来:

a=44 b=117 c=240
a=85 b=132 c=720
a=88 b=234 c=480
a=132 b=351 c=720
a=140 b=480 c=693
a=160 b=231 c=792
a=176 b=468 c=960
a=240 b=252 c=275
a=480 b=504 c=550
a=720 b=756 c=825

如果
a
b
ab
没有形成毕达哥拉斯三元组,也许可以跳过最里面的循环。我的意思是,你可以在
c
-循环之前计算
ab
,如果
ab
不是整数,那么运行整个
c
-循环有什么意义呢?@Aaron_ab:这是一个Python习语,用来检查浮点值是否是整数(即等于整数).我们能更详细地了解一下你遗漏了什么吗?以合理的效率获取所有原始三元组;你的“洞”在哪里?