[Python] What is the best way to generate Pythagorean triples?

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    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...

    Continue reading...

Compartilhe esta Página