Find Pythagorean triplet for which a + b + c = 1000

后端 未结 16 2421
离开以前
离开以前 2020-12-24 13:13

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 4

16条回答
  •  时光说笑
    2020-12-24 13:46

    Here's a solution using Euclid's formula (link).

    Let's do some math: In general, every solution will have the form

    a=k(x²-y²)
    b=2kxy
    c=k(x²+y²)
    

    where k, x and y are positive integers, y < x and gcd(x,y)=1 (We will ignore this condition, which will lead to additional solutions. Those can be discarded afterwards)

    Now, a+b+c= kx²-ky²+2kxy+kx²+ky²=2kx²+2kxy = 2kx(x+y) = 1000

    Divide by 2: kx(x+y) = 500

    Now we set s=x+y: kxs = 500

    Now we are looking for solutions of kxs=500, where k, x and s are integers and x < s < 2x. Since all of them divide 500, they can only take the values 1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500. Some pseudocode to do this for arbitrary n (it and can be done by hand easily for n=1000)

    If n is odd
      return "no solution"
    else
      L = List of divisors of n/2
    for x in L
      for s in L
        if x< s <2*x and n/2 is divisible by x*s
          y=s-x
          k=((n/2)/x)/s      
          add (k*(x*x-y*y),2*k*x*y,k*(x*x+y*y)) to list of solutions
    sort the triples in the list of solutions
    delete solutions appearing twice
    return list of solutions
    

    You can still improve this:

    • x will never be bigger than the root of n/2
    • the loop for s can start at x and stop after 2x has been passed (if the list is ordered)

    For n = 1000, the program has to check six values for x and depending on the details of implementation up to one value for y. This will terminate before you release the button.

提交回复
热议问题