From a7075a579cc29786c94d103411ef1072a8cba461 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Sat, 8 Feb 2020 16:39:32 +0100 Subject: [PATCH] Fix: Problem 39: Integer right triangles (#38145) * fix: correct test and add solution I also changed the seed to report the results of an easier example to the user, since just evaluating the function mostly wastes time. * fix: use a better solution * fix: credit original author --- ...blem-39-integer-right-triangles.english.md | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-39-integer-right-triangles.english.md b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-39-integer-right-triangles.english.md index e6d93aac26..8e7711d938 100644 --- a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-39-integer-right-triangles.english.md +++ b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-39-integer-right-triangles.english.md @@ -24,8 +24,8 @@ For which value of p ≤ n, is the number of solutions maximised? tests: - text: intRightTriangles(500) should return 420. testString: assert(intRightTriangles(500) == 420); - - text: intRightTriangles(800) should return 420. - testString: assert(intRightTriangles(800) == 420); + - text: intRightTriangles(800) should return 720. + testString: assert(intRightTriangles(800) == 720); - text: intRightTriangles(900) should return 840. testString: assert(intRightTriangles(900) == 840); - text: intRightTriangles(1000) should return 840. @@ -46,7 +46,7 @@ function intRightTriangles(n) { return n; } -intRightTriangles(1000); +console.log(intRightTriangles(500)); // 420 ``` @@ -59,7 +59,34 @@ intRightTriangles(1000);
```js -// solution required + +// Original idea for this solution came from +// https://www.xarg.org/puzzle/project-euler/problem-39/ + +function intRightTriangles(n) { + // store the number of triangles with a given perimeter + let triangles = {}; + // a is the shortest side + for (let a = 3; a < n / 3; a++) + // o is the opposite side and is at least as long as a + for (let o = a; o < n / 2; o++) { + let h = Math.sqrt(a * a + o * o); // hypotenuse + let p = a + o + h; // perimeter + if ((h % 1) === 0 && p <= n) { + triangles[p] = (triangles[p] || 0) + 1; + } + } + + let max = 0, maxp = null; + for (let p in triangles) { + if (max < triangles[p]) { + max = triangles[p]; + maxp = p; + } + } + return maxp; +} + ```