2.4 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			2.4 KiB
		
	
	
	
	
	
	
	
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName | 
|---|---|---|---|---|
| 5900f3c11000cf542c50fed4 | Problema 85: Contagem de retângulos | 5 | 302199 | problem-85-counting-rectangles | 
--description--
Se contarmos com cuidado, poderemos ver que uma grade retangular que mede 3 por 2 contém dezoito retângulos:
 
Embora possa não existir uma grade retangular que contenha exatamente n retângulos, calcule a área da grade com a solução mais próxima.
--hints--
countingRectangles(18) deve retornar um número.
assert(typeof countingRectangles(18) === 'number');
countingRectangles(18) deve retornar 6.
assert.strictEqual(countingRectangles(18), 6);
countingRectangles(250) deve retornar 22.
assert.strictEqual(countingRectangles(250), 22);
countingRectangles(50000) deve retornar 364.
assert.strictEqual(countingRectangles(50000), 364);
countingRectangles(1000000) deve retornar 1632.
assert.strictEqual(countingRectangles(1000000), 1632);
countingRectangles(2000000) deve retornar 2772.
assert.strictEqual(countingRectangles(2000000), 2772);
--seed--
--seed-contents--
function countingRectangles(n) {
  return true;
}
countingRectangles(18);
--solutions--
function countingRectangles(n) {
  function numberOfRectangles(h, w) {
    return (h * (h + 1) * w * (w + 1)) / 4;
  }
  function rectangleArea(h, w) {
    return h * w;
  }
  let rectanglesCount = 1;
  let maxSide = 1;
  while (rectanglesCount < n) {
    maxSide++;
    rectanglesCount = numberOfRectangles(maxSide, 1);
  }
  let bestDiff = Math.abs(rectanglesCount - n);
  let bestSize = [maxSide, 1];
  let curHeight = maxSide - 1;
  let curWidth = 1;
  for (curWidth; curWidth < curHeight; curWidth++) {
    for (curHeight; curHeight > curWidth; curHeight--) {
      rectanglesCount = numberOfRectangles(curHeight, curWidth);
      const curDiff = Math.abs(rectanglesCount - n);
      if (curDiff < bestDiff) {
        bestDiff = curDiff;
        bestSize = [curHeight, curWidth];
      }
      if (rectanglesCount < n) {
        break;
      }
    }
  }
  return rectangleArea(...bestSize);
}