Back to Freecodecamp

Challenge 205: Perfect Cube Count

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa8.md

latest1.3 KB
Original Source

--description--

Given two integers, determine how many perfect cubes exist in the range between and including the two numbers.

  • The lower number is not guaranteed to be the first argument.
  • A number is a perfect cube if there exists an integer (n) where n * n * n = number. For example, 27 is a perfect cube because 3 * 3 * 3 = 27.

--hints--

countPerfectCubes(3, 30) should return 2.

js
assert.equal(countPerfectCubes(3, 30), 2);

countPerfectCubes(1, 30) should return 3.

js
assert.equal(countPerfectCubes(1, 30), 3);

countPerfectCubes(30, 0) should return 4.

js
assert.equal(countPerfectCubes(30, 0), 4);

countPerfectCubes(-64, 64) should return 9.

js
assert.equal(countPerfectCubes(-64, 64), 9);

countPerfectCubes(9214, -8127) should return 41.

js
assert.equal(countPerfectCubes(9214, -8127), 41);

--seed--

--seed-contents--

js
function countPerfectCubes(a, b) {

  return a;
}

--solutions--

js
function countPerfectCubes(a, b) {
  const start = Math.min(a, b);
  const end = Math.max(a, b);

  let count = 0;
  let n = 0;

  while (n ** 3 <= end) {
    if (n ** 3 >= start) count++;
    n++;
  }

  n = -1;
  while (n ** 3 >= start) {
    if (n ** 3 <= end) count++;
    n--;
  }

  return count;
}