Generating unique, ordered Pythagorean triplets

前端 未结 19 1189
借酒劲吻你
借酒劲吻你 2020-11-29 16:57

This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can

相关标签:
19条回答
  • 2020-11-29 17:55

    I wrote that program in Ruby and it similar to the python implementation. The important line is:

    if x*x == y*y + z*z && gcd(y,z) == 1:
    

    Then you have to implement a method that return the greatest common divisor (gcd) of two given numbers. A very simple example in Ruby again:

    def gcd(a, b)
        while b != 0
          t = b
          b = a%b
          a = t
        end
        return a
    end
    

    The full Ruby methon to find the triplets would be:

    def find_triple(upper_boundary)
    
      (5..upper_boundary).each {|c|
        (4..c-1).each {|b|
          (3..b-1).each {|a|
            if (a*a + b*b == c*c && gcd(a,b) == 1)
              puts "#{a} \t #{b} \t #{c}"
            end
          }
        }
      }
    end
    
    0 讨论(0)
提交回复
热议问题