|
1 | 1 | package com.thealgorithms.maths;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * https://en.wikipedia.org/wiki/Pythagorean_triple |
| 4 | + * Utility class to check if three integers form a Pythagorean triple. |
| 5 | + * A Pythagorean triple consists of three positive integers a, b, and c, |
| 6 | + * such that a² + b² = c². |
| 7 | + * |
| 8 | + * Common examples: |
| 9 | + * - (3, 4, 5) |
| 10 | + * - (5, 12, 13) |
| 11 | + * |
| 12 | + * Reference: https://en.wikipedia.org/wiki/Pythagorean_triple |
5 | 13 | */
|
6 | 14 | public final class PythagoreanTriple {
|
7 |
| - private PythagoreanTriple() { |
8 |
| - } |
9 | 15 |
|
10 |
| - public static void main(String[] args) { |
11 |
| - assert isPythagTriple(3, 4, 5); |
12 |
| - assert isPythagTriple(5, 12, 13); |
13 |
| - assert isPythagTriple(6, 8, 10); |
14 |
| - assert !isPythagTriple(10, 20, 30); |
15 |
| - assert !isPythagTriple(6, 8, 100); |
16 |
| - assert !isPythagTriple(-1, -1, 1); |
| 16 | + private PythagoreanTriple() { |
17 | 17 | }
|
18 | 18 |
|
19 | 19 | /**
|
20 |
| - * Check if a,b,c are a Pythagorean Triple |
| 20 | + * Checks whether three integers form a Pythagorean triple. |
| 21 | + * The order of parameters does not matter. |
21 | 22 | *
|
22 |
| - * @param a x/y component length of a right triangle |
23 |
| - * @param b y/x component length of a right triangle |
24 |
| - * @param c hypotenuse length of a right triangle |
25 |
| - * @return boolean <tt>true</tt> if a, b, c satisfy the Pythagorean theorem, |
26 |
| - * otherwise |
27 |
| - * <tt>false</tt> |
| 23 | + * @param a one side length |
| 24 | + * @param b another side length |
| 25 | + * @param c another side length |
| 26 | + * @return {@code true} if (a, b, c) can form a Pythagorean triple, otherwise {@code false} |
28 | 27 | */
|
29 | 28 | public static boolean isPythagTriple(int a, int b, int c) {
|
30 | 29 | if (a <= 0 || b <= 0 || c <= 0) {
|
31 | 30 | return false;
|
32 |
| - } else { |
33 |
| - return (a * a) + (b * b) == (c * c); |
34 | 31 | }
|
| 32 | + |
| 33 | + // Sort the sides so the largest is treated as hypotenuse |
| 34 | + int[] sides = {a, b, c}; |
| 35 | + java.util.Arrays.sort(sides); |
| 36 | + |
| 37 | + int x = sides[0]; |
| 38 | + int y = sides[1]; |
| 39 | + int hypotenuse = sides[2]; |
| 40 | + |
| 41 | + return x * x + y * y == hypotenuse * hypotenuse; |
35 | 42 | }
|
36 | 43 | }
|
0 commit comments