|
1 |
| -// Check if triplet holds invariant a² + b² = c² |
2 |
| -const isSquareValid = ([a, b, c]) => a ** 2 + b ** 2 === c ** 2 |
3 |
| - |
4 |
| -// Check if triplet holds invariant a + b + c = targetSum |
5 |
| -const isSumValid = ([a, b, c], targetSum) => a + b + c === targetSum |
6 |
| - |
7 |
| -// Check if triplet holds invariant a < b < c |
8 |
| -const isRelValid = ([a, b, c]) => a < b && b < c |
9 |
| - |
10 |
| -// Throws an error if triplet doesn't hold sum or relation invariants |
11 |
| -const validateTriplet = (triplet, targetSum) => { |
12 |
| - if (!isSumValid(triplet, targetSum) || !isRelValid(triplet)) { |
13 |
| - throw new Error(`Invalid triplet ${triplet}`) |
14 |
| - } |
15 |
| -} |
16 |
| - |
17 |
| -// Computes next triplet iteration, while holding sum and relation invariants |
18 |
| -const increaseTriplet = (triplet, targetSum) => { |
19 |
| - const [a, b, c] = triplet |
20 |
| - |
21 |
| - validateTriplet(triplet, targetSum) |
22 |
| - |
23 |
| - if (b + 2 < c) { |
24 |
| - triplet[1] = b + 1 |
25 |
| - triplet[2] = c - 1 |
26 |
| - } else { |
27 |
| - triplet[0] = a + 1 |
28 |
| - triplet[1] = a + 2 |
29 |
| - triplet[2] = targetSum - triplet[0] - triplet[1] |
30 |
| - } |
31 |
| -} |
32 |
| - |
33 | 1 | /**
|
34 | 2 | * Compute the product of the pythagorean triplet where a + b + c = targetSum.
|
| 3 | + * |
35 | 4 | * @param {number} targetSum Sum of triplet must equal this value.
|
36 | 5 | * @throws {Error} If an invalid triplet is ever reached.
|
37 | 6 | * @returns {number} Product of triplet found, where a + b + c = targetSum.
|
38 | 7 | */
|
39 | 8 | const specialPythagoreanTriplet = (targetSum) => {
|
40 |
| - const triplet = [1, 2, targetSum - 3] |
41 |
| - |
42 |
| - while (!isSquareValid(triplet)) { |
43 |
| - increaseTriplet(triplet, targetSum) |
| 9 | + const tri = [1, 2, targetSum - 3] |
| 10 | + |
| 11 | + while (!(tri[0] ** 2 + tri[1] ** 2 === tri[2] ** 2)) { |
| 12 | + const [a, b, c] = tri |
| 13 | + |
| 14 | + const isSumTarget = a + b + c === targetSum |
| 15 | + const isAscending = a < b && b < c |
| 16 | + |
| 17 | + if (!isSumTarget || !isAscending) { |
| 18 | + throw new Error(`Invalid triplet ${[a, b, c]}`) |
| 19 | + } |
| 20 | + |
| 21 | + if (b + 2 < c) { |
| 22 | + tri[1] = b + 1 |
| 23 | + tri[2] = c - 1 |
| 24 | + } else { |
| 25 | + tri[0] = a + 1 |
| 26 | + tri[1] = a + 2 |
| 27 | + tri[2] = targetSum - tri[0] - tri[1] |
| 28 | + } |
44 | 29 | }
|
45 | 30 |
|
46 |
| - return triplet.reduce((acc, num) => acc * num) |
| 31 | + return tri[0] * tri[1] * tri[2] |
47 | 32 | }
|
48 | 33 |
|
49 | 34 | module.exports = {
|
|
0 commit comments