What is the best way to generate Pythagorean triples?

社会主义新天地 提交于 2019-12-04 17:14:50

I was curious so I decided to try this. I found that this algorithm was pretty easy to implement in Python and works pretty fast:

import math                                                                 

def pythagorean_triples(n):                                                 
    a, b, c = 1, 3, 0                                                       
    while c < n:                                                            
        a_ = (a * b) + a                                                    
        c = math.sqrt(a_**2 + b**2)                                         
        if c == int(c):                                                     
            yield b, a_, int(c)                                             
        a += 1                                                              
        b += 2                                                              

if __name__ == '__main__':                                                  
    import sys                                                              
    for pt in pythagorean_triples(int(sys.argv[1])):                        
        print(pt)

Try it by copying that script into pythagorean_triples.py and running python3 pythagorean_triples.py n where n is the maximum c you want it to generate. (You can use later Python2 if you like as well.)

The Wikipedia page on Pythagorean triples gives us a hint:

The triple generated by Euclid's formula is primitive if and only if m and n are coprime and m − n is odd. If both m and n are odd, then a, b, and c will be even, and so the triple will not be primitive; however, dividing a, b, and c by 2 will yield a primitive triple if m and n are coprime

If you restrict m and n to coprime numbers and force m - n to be odd you will uiniquely generate all the primitive pythagorean triples. From this point on, you should be able to multiply these unique triples by factors of d to uniquely generate all triples.

In your example, allowing n=7 and m=5 was the problem, because their difference was even and the triple they generated was not primitive (you could divide all sides by 2 to get a smaller triple)

Here is my solution:

import math
def pythagoreanTriplet(n):
  for b in range(n):
    for a in range(1, b):
        c = math.sqrt( a * a + b * b)
        if c % 1 == 0:
            print (a, b, int(c))

pythagoreanTriplet(12)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!