Created
June 4, 2023 15:04
-
-
Save merryt/dee546e5d3d682d09f42a941f2dc3701 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const checkIfPythagTriplet = (a, b, c) => (c * c) === (a * a) + (b * b) | |
| const targetSum = 1000 | |
| /// slow loopy way | |
| // I don't know exactly which big O notation this is, but its bad.... | |
| // when I check the time on this one (running it up to product of 10,000 on my local machine takes 114.67s ) | |
| let a = 1; | |
| let b = 1; | |
| let c = 2; | |
| for (c = 2; c + b + a <= targetSum; c++) { | |
| for (b = 1; b < c; b++) { | |
| for (a = 1; a < b; a++) { | |
| if (a + b + c === 1000 && checkIfPythagTriplet(a, b, c)) { | |
| console.log(`a: ${a},b: ${b},c:${c}, product: ${a + b + c}`); | |
| } | |
| } | |
| a = 1; | |
| } | |
| b = 1; | |
| } | |
| // Skipping Aiming for ONLY the product sum instead of all product sums along the way, | |
| for (let a = 3; a < (targetSum - 3) / 3; a++) { | |
| for (let b = a + 1; b < (targetSum - a - 1) / 2; b++) { | |
| const c = targetSum - a - b; | |
| if (a + b + c === 1000 && checkIfPythagTriplet(a, b, c)) { | |
| console.log(`HIT: a: ${a},b: ${b},c:${c}, product: ${a + b + c}`); | |
| } | |
| } | |
| } | |
| /// recursive varient | |
| /// has the same performance issues | |
| const lookForPythagTriplet = (a, b, c, targetSum) => { | |
| console.log(`a: ${a},b: ${b},c:${c}. targetSum: ${targetSum}, btarget: ${(targetSum - a - 1) / 2}`); | |
| if (checkIfPythagTriplet(a, b, c)) { | |
| console.log(`HIT: a: ${a},b: ${b},c:${c}, product: ${a + b + c}`); | |
| } | |
| if (b < (targetSum - a - 1) / 2) { | |
| lookForPythagTriplet(a, b + 1, targetSum - a - b - 1, targetSum) | |
| } else if (a < (targetSum - 3) / 3) { | |
| lookForPythagTriplet(a + 1, a + 2, targetSum - a - b - 1, targetSum) | |
| } | |
| } | |
| lookForPythagTriplet(2, 3, 5, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment