Skip to content

Commit b22ab2a

Browse files
committed
fix(maths): prevent 32-bit integer overflow in PythagoreanTriple
1 parent c1a7f8d commit b22ab2a

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

‎src/main/java/com/thealgorithms/maths/PythagoreanTriple.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ public static boolean isPythagTriple(int a, int b, int c) {
3434
int[] sides = {a, b, c};
3535
java.util.Arrays.sort(sides);
3636

37-
int x = sides[0];
38-
int y = sides[1];
39-
int hypotenuse = sides[2];
37+
long x = sides[0];
38+
long y = sides[1];
39+
long hypotenuse = sides[2];
4040

4141
return x * x + y * y == hypotenuse * hypotenuse;
4242
}

‎src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,24 @@
1010
public class PythagoreanTripleTest {
1111

1212
@ParameterizedTest
13-
@CsvSource({"3, 4, 5, true", "6, 8, 10, true", "9, 12, 15, true", "12, 16, 20, true", "15, 20, 25, true", "18, 24, 30, true", "5, 20, 30, false", "6, 8, 100, false", "-2, -2, 2, false", "0, 0, 0, false", "5, 5, 5, false"})
13+
@CsvSource({
14+
"3, 4, 5, true",
15+
"6, 8, 10, true",
16+
"9, 12, 15, true",
17+
"12, 16, 20, true",
18+
"15, 20, 25, true",
19+
"18, 24, 30, true",
20+
"30000, 40000, 50000, true",
21+
"60000, 80000, 100000, true",
22+
"100000, 240000, 260000, true",
23+
"30000, 40000, 50001, false",
24+
"65536, 65536, 65536, false",
25+
"5, 20, 30, false",
26+
"6, 8, 100, false",
27+
"-2, -2, 2, false",
28+
"0, 0, 0, false",
29+
"5, 5, 5, false"
30+
})
1431
void testIsPythagoreanTriple(int a, int b, int c, boolean expected) {
1532
assertEquals(expected, PythagoreanTriple.isPythagTriple(a, b, c));
1633
}

0 commit comments

Comments
 (0)