Finding number of open water taps after n chances using JavaScript

JavascriptWeb DevelopmentFront End Technology

<h2>Problem</h2><p>Suppose a school organises this game on their Annual Day celebration &minus;</p><p>There are &rdquo;n&rdquo; water taps and &ldquo;n&rdquo; 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 &quot;n&quot;th student, how many taps are open?</p><p>We are required to write a JavaScript function that takes in the number n and returns the number of open water taps.</p><h2>Example</h2><p>Following is the code &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notransalte">const num = 15; const openTaps = (num = 1) =&gt; { &nbsp; &nbsp;const arr = []; &nbsp; &nbsp;let index = 1; &nbsp; &nbsp;while(index ** 2 &lt;= num){ &nbsp; &nbsp; &nbsp; arr.push(index++ ** 2); &nbsp; &nbsp;}; &nbsp; &nbsp;return arr.length; }; console.log(openTaps(num));</pre><h2>Output</h2><pre class="result notransalte">7</pre>
Updated on 19-Apr-2021 11:21:58