Switching on and off bulb in JavaScript


Problem

Consider this following situation −

There are n bulbs that are initially off. We first turn on all the bulbs. Then, we turn off every second bulb. On the third round, we toggle every third bulb (turning on if it's off or turning off if it's on).

In general, for the ith round, we toggle every i bulb. And lastly for the nth round, we only toggle the last bulb.

We are required to write a JavaScript function that takes n as the only input and finds out how many bulbs are on after n rounds.

For example, if the input to the function is −

const n = 4;

Then the output should be −

const output = 2;

Output Explanation:

In the state array, a 0 indicates off whereas 1 indicates on −

RoundState
1[1, 1, 1, 1, 1]
2[1, 0, 1, 0, 1]
3[1, 0, 0, 0, 1]
4[1, 0, 0, 1, 1]
5[1, 0, 0, 1, 0]

Hence after the fifth round only two bulbs are on.

Example

The code for this will be −

const n = 5;
const findOn = (n = 1) => {
   let off = 0;
   let on = n;
   while(off <= on){
      let mid = Math.floor((off + on) / 2);
      if(mid * mid > n){
         on = mid - 1;
      }else{
         off = mid + 1;
      };
   };
   return Math.floor(on);
};
console.log(findOn(n));

Output

And the output in the console will be −

2

Updated on: 20-Mar-2021

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements