AdSense

Monday, June 13, 2016

Bulb Switcher

There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3. 

At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off]. 

So you should return 1, because there is only one bulb is on.

Update 2016-10-11

This problem is more like a math problem. For bulb i, if its number of factors is odd, it will be turned on in the end, if its number of factors is even, it will be turned off in the end. However, only the square root of n has odd factors because all other factors exists in pair. For example, n = 36, its factors are (1, 36), (2, 18),  (3, 12), (4, 9), (6, 6), (9, 4), (12, 3), (18, 2), (1, 36).



I don't really like mathematical problems, part of the reason is that I'm not good at it. This problem is a typical math problem. And the code is:

public int bulbSwitch(int n) {
        if (n < 0)
            return 0;
        return (int)Math.sqrt(n);
        
    }


So easy, right? So why this is the case.

For every prime number, it only contains factor of 1 and itself, which means it will ultimately be turned off (turn on at 1st round and turn off at the-number-itself round).
For every square number, in the end it will be turned on because all other factors will be in pairs except its square root. Consider 4:
1 * 4, 2 * 2, 4 * 1
At first round, it will be the forth to turn on, off -> on
At second round, it will be the second to turn off, on -> off
At round four, it will be the first to turn on, off -> on

Consider 9:
1 * 9, 3 * 3, 9 * 1

For all other numbers, it will be turned off ultimately because all the factors are in pairs.

So the number of turned on lights depends on how many square number n has, which is its square root.

No comments:

Post a Comment