Skip to content

Commit 8b2d001

Browse files
committed
feat(day 159): check if right triangle hypotenuse is an integer using Pythagorean theorem
1 parent 908e47b commit 8b2d001

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
3+
Integer Hypotenuse
4+
Given two positive integers representing the lengths for the two legs (the two short sides) of a right triangle, determine whether the hypotenuse is an integer.
5+
6+
The length of the hypotenuse is calculated by adding the squares of the two leg lengths together and then taking the square root of that total (a2 + b2 = c2).
7+
"""
8+
9+
import math, unittest
10+
11+
class IntegerHypotenuseTest(unittest.TestCase):
12+
13+
def test1(self):
14+
self.assertEqual(is_integer_hypotenuse(3, 4), True)
15+
16+
def test2(self):
17+
self.assertEqual(is_integer_hypotenuse(2, 3), False)
18+
19+
def test3(self):
20+
self.assertEqual(is_integer_hypotenuse(5, 12), True)
21+
22+
def test4(self):
23+
self.assertEqual(is_integer_hypotenuse(10, 10), False)
24+
25+
def test5(self):
26+
self.assertEqual(is_integer_hypotenuse(780, 1040), True)
27+
28+
def test6(self):
29+
self.assertEqual(is_integer_hypotenuse(250, 333), False)
30+
31+
32+
def is_integer_hypotenuse(a, b):
33+
34+
c = math.sqrt(a**2 + b**2)
35+
36+
return c.is_integer()
37+
38+
39+
"""
40+
=> This is essentially checking if (a, b, c) form a Pythagorean triple.
41+
=> .is_integer() in Python or Number.isInteger() in JS ensures the hypotenuse is a whole number.
42+
=> Example of integer hypotenuses: (3, 4, 5), (5, 12, 13), (8, 15, 17).
43+
"""
44+
if __name__ == "__main__":
45+
print(is_integer_hypotenuse(3, 4))
46+
unittest.main()
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
A Pythagorean triple is a set of integers (a, b, c) such that: a^2 + b^2 = c^2
3+
4+
where c is the hypotenuse.
5+
6+
We want all triples with c <= N.
7+
"""
8+
9+
import math
10+
11+
def pythagorean_triples(limit):
12+
13+
triples = []
14+
for a in range(1, limit):
15+
for b in range(a, limit):
16+
17+
c2 = a*a + b*b
18+
c = int(math.isqrt(c2))
19+
20+
if c*c == c2 and c <= limit:
21+
triples.append((a, b, c))
22+
23+
return triples
24+
25+
26+
27+
"""
28+
=> We loop over possible legs a and b.
29+
=> Compute c2 = a2 + b2
30+
=> If c2 is a perfect square, we've found a triple.
31+
=> Restrict c <= limit.
32+
=> This finds primitive triples (like (3, 4, 5)) and multiples (like (6,8, 10))
33+
"""
34+
35+
if __name__ == "__main__":
36+
37+
print(pythagorean_triples(20))

0 commit comments

Comments
 (0)