What is the best way to generate Pythagorean triples?
Question: I have tried with that simple code when you just check all the combinations
for a and b and then check if square root of c is an integer, but that code is
really slow, then I have tried with Euclid's formula

    
    
    a = d*(n^2 - m^2)
    b = 2*n*m*d
    c = d*(n^2 + m^2)
    

and I have written a code where you first find n with

    
    
    trunc(sqrt(max_value))
    //this is in pascal
    

and then you check every combination of 0 < m < n but I get duplicate results,
like if n is 7, m is 5 and d is 1, and n is 6, m is 1 and d is 2 . In both
cases you get 24, 70 and 74. So what is a good fast way to calculate the
number of Pythagorean triples, I can't seem to find a way, also if I add all
results to an array, and then check the array for duplicates, it just takes
too much time... If anyone can help me with the code it can be pascal, c or
python, I can understand all...


Answer: I was curious so I decided to try this. I found that [this
algorithm](http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples#Progressions_of_whole_and_fractional_numbers)
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.)

