freeCodeCamp Challenge Guide: 100 doors

100 doors


Solutions

Solution 1 (Click to Show/Hide)
function getFinalOpenedDoors(numDoors) {
  let doors = [];
  let i = 1, ii = i*i;

  while (ii <= numDoors) {
    doors.push(ii);
    i++; ii = i*i;
  }

  return doors;
}

Code Explanation

Each door is open if it is visited an odd number of times. Each door is visited once for each number that divides into it. Therefore, each open door has an odd number of divisors.

But divisors come in pairs: a / b === c means that a === b * c and b and c divide evenly into a .

So the only way to have an odd number of divisors is if for one of the pairs of divisors b === c , which means a === b * b is a perfect square.

2 Likes