Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-39-integer-right-triangles.english.md
Kristofer Koishigawa 6cfd0fc503 fix: improve Project Euler descriptions, challenge seeds, and test cases (#38016)
* fix: improve Project Euler descriptions and test case

Improve formatting of Project Euler test descriptions. Also add poker hands array and new test case for problem 54

* feat: add typeof tests and gave functions proper names for first 100 challenges

* fix: continue fixing test descriptions and adding "before test" sections

* fix: address review comments

* fix: adjust grids in 18 and 67 and fix some text that reference files rather than the given arrays

* fix: implement bug fixes and improvements from review

* fix: remove console.log statements from seed and solution
2020-02-28 06:39:47 -06:00

2.1 KiB

id, challengeType, title, forumTopicId
id challengeType title forumTopicId
5900f3931000cf542c50fea6 5 Problem 39: Integer right triangles 302054

Description

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of pn, is the number of solutions maximized?

Instructions

Tests

tests:
  - text: <code>intRightTriangles(500)</code> should return a number.
    testString: assert(typeof intRightTriangles(500) === 'number');
  - text: <code>intRightTriangles(500)</code> should return 420.
    testString: assert(intRightTriangles(500) == 420);
  - text: <code>intRightTriangles(800)</code> should return 720.
    testString: assert(intRightTriangles(800) == 720);
  - text: <code>intRightTriangles(900)</code> should return 840.
    testString: assert(intRightTriangles(900) == 840);
  - text: <code>intRightTriangles(1000)</code> should return 840.
    testString: assert(intRightTriangles(1000) == 840);

Challenge Seed

function intRightTriangles(n) {
  // Good luck!
  return n;
}

intRightTriangles(500);

Solution


// 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 = parseInt(p);
    }
  }
  return maxp;
}