Law of cosines - triples

From Rosetta Code
Revision as of 01:01, 23 September 2018 by rosettacode>Paddy3118 (New draft task with python example.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A² + B² - 2ABcos(γ) = C²

Specific angles

For an angle of of 90° this becomes the more familiar "Pythagoras equation:
A² + B² = C²

For an angle of of 60° this becomes the less familiar equation:
A² + B² - AB = C²

And finally or an angle of of 120° this becomes the equation:
A² + B² + AB = C²

Task
  • Find all integer solutions to the three specific cases, in order; distinguishing between each angle being considered.
  • Restrain all sides to the integers 1..13 inclusive.
  • Show how many results there are for each angle.
  • Display results on this page.

Python

<lang>N = 13

def method1(N=N):

   squares = [x**2 for x in range(0, N+1)]
   sqrset = set(squares)
   tri90, tri60, tri120 = (set() for _ in range(3))
   for a in range(1, N+1):
       a2 = squares[a]
       for b in range(1, a + 1):
           b2 = squares[b]
           c2 = a2 + b2
           if c2 in sqrset:
               tri90.add(tuple(sorted((a, b, int(c2**0.5)))))
               continue
           ab = a * b
           c2 -= ab
           if c2 in sqrset:
               tri60.add(tuple(sorted((a, b, int(c2**0.5)))))
               continue
           c2 += 2 * ab
           if c2 in sqrset:
               tri120.add(tuple(sorted((a, b, int(c2**0.5)))))
   return  sorted(tri90), sorted(tri60), sorted(tri120)
  1. %%

if __name__ == '__main__':

   print(f'Integer triangular triples for sides 1..{N}:')
   for angle, triples in zip([90, 60, 120], method1(N)):
       print(f'  {angle:3}° has {len(triples)} solutions:\n    {triples}')</lang>
Output:
Integer triangular triples for sides 1..13:
   90° has 3 solutions:
    [(3, 4, 5), (5, 12, 13), (6, 8, 10)]
   60° has 15 solutions:
    [(1, 1, 1), (2, 2, 2), (3, 3, 3), (3, 7, 8), (4, 4, 4), (5, 5, 5), (5, 7, 8), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9), (10, 10, 10), (11, 11, 11), (12, 12, 12), (13, 13, 13)]
  120° has 2 solutions:
    [(3, 5, 7), (7, 8, 13)]