Finding number of open water taps after n chances using JavaScript


Suppose a school organises this game on their Annual Day celebration −

There are ”n” water taps and “n” students are chosen at random. The instructor asks the first student to go to every tap and open it. Then he has the second student go to every second tap and close it. The third goes to every third tap and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth tap, and so on. After the process is completed with the "n"th student, how many taps are open?

We are required to write a JavaScript function that takes in the number n and returns the number of open water taps.


Following is the code −

 Live Demo

const num = 15;
const openTaps = (num = 1) => {
   const arr = [];
   let index = 1;
   while(index ** 2 <= num){
      arr.push(index++ ** 2);
   return arr.length;