Bulb Switcher

Find how many of n bulbs stay on after n rounds of switching, by counting perfect squares.

There are n bulbs in a row, numbered 1 to n, and all of them start off. In round 1 you turn every bulb on. In round 2 you toggle every 2nd bulb, which means turning it off if it is on and on if it is off. In round 3 you toggle every 3rd bulb, and so on, until round n toggles only bulb n. Given n, zero or more, return how many bulbs are on after the last round.

Example 1
Input: n = 3
Output: 1
Explanation: after rounds 1, 2 and 3 the bulbs are [on, on, on], [on, off, on] and [on, off, off].
Example 2
Input: n = 0
Output: 0
Solution

The Idea

Picture a hallway with ten ceiling bulbs, numbered 1 to 10, each with its own switch. Ten people walk down the hallway one after another. The first flips every switch, the second flips every 2nd switch, the third every 3rd, and the tenth flips only the switch of bulb 10. Which bulbs are lit when the tenth person has passed?

The grid below follows all ten rounds. Each column is a bulb, each row is a round, and a blue dot marks a bulb that the round toggles.

Ten bulbs and ten rounds. A blue dot marks each round that toggles a bulb. Bulbs 1, 4 and 9 are toggled 1, 3 and 3 times and end on; every other bulb is toggled an even number of times and ends off.

Follow the column of bulb 6 down. Rounds 1, 2, 3 and 6 toggle it, so it goes on, off, on and off again. The row labelled "times toggled" shows 4 for it, and the row labelled "at the end" shows it off. Bulb 4 has dots in rounds 1, 2 and 4 only: on, off, on. It is toggled 3 times and stays on.

So a bulb ends on exactly when it is toggled an odd number of times. Which rounds toggle bulb 6? Round r reaches bulbs r, 2r, 3r and so on, so it toggles bulb 6 when 6 is a multiple of r. That happens for 1, 2, 3 and 6, the numbers that divide 6 with no remainder, which are called the divisors of 6.

Why do most bulbs get an even count? Divisors come in pairs that multiply to the bulb's number. For 6 the pairs are 1 × 6 and 2 × 3, four divisors in all. For 9 they are 1 × 9 and 3 × 3, and the second pair is 3 with itself, so 9 has three divisors: 1, 3 and 9.

A divisor pairs with itself only when the bulb's number is some whole number times itself. Such a number, like 1, 4 or 9, is called a perfect square. That is why the orange columns in the picture, bulbs 1, 4 and 9, are the ones that end on. The answer is the number of perfect squares from 1 to n.

Solution Approach

Three things remain to settle: why flipping the bulbs round by round is the slow way, how to count the perfect squares up to n, and how to turn a square root into a whole number without mistakes.

Simulating the rounds

Why not just flip the bulbs? An array with one true or false entry per bulb, a loop over the rounds, and inside it a loop that steps through every r-th bulb give the right answer. Round r touches about n / r bulbs, so the toggles add up to n/1 + n/2 + ... + n/n.

For ten bulbs that is the 27 dots in the picture. For a billion bulbs it is 20,877,697,634 toggles, on an array of a billion entries. The perfect squares give the same count with no array at all.

Counting the perfect squares up to n

How many perfect squares lie between 1 and n? They are 1 × 1, 2 × 2, 3 × 3 and so on, and k × k stays at or below n for every whole k up to the square root of n, written √n. So the count is the whole part of √n. For ten bulbs, √10 is about 3.16, and its whole part, 3, counts 1, 4 and 9. For nine bulbs the root is exactly 3, and bulb 9 itself is counted.

Turning the square root into a whole number

What does Java give for √n? Math.sqrt(n) returns a double, a number with a fraction part. Writing (int) in front of it drops the fraction, so (int) Math.sqrt(10) is 3. Rounding instead would count a square that lies above n. For three bulbs, √3 is about 1.73, and Math.round(Math.sqrt(3)) gives 2, yet only bulb 1 is on.

Could the double be a hair too small, say 2.9999 for √9, so that dropping the fraction loses one? Every int fits in a double exactly. A run that tried every k from 1 to 46,340 found (int) Math.sqrt correct both at k × k and one below it. That covers every perfect square an int can hold, since 46,340 × 46,340 is 2,147,395,600 and the next square is too big.

The square root also keeps the code away from multiplying. A loop that counts k upward while k * k <= n looks just as correct. With k as an int and n = Integer.MAX_VALUE (2,147,483,647), though, 46,341 × 46,341 wraps around to -2,147,479,015, which is still below n. A test run of that loop was still going after 100,000 steps, so it had to be stopped by a step limit.

Java Solution

The method bulbSwitch works in two steps:

  1. First, take the square root of n with Math.sqrt(n). It returns a double, about 3.16 for n = 10.
  2. Then cast that root to int, which drops the fraction and leaves the number of perfect squares from 1 to n, 3 for n = 10. Return it as the number of bulbs that are on.

A helper method, simulate, does the slow way for comparison: it flips the bulbs round by round in a boolean array named on and counts the ones left on. The main method runs both examples, n = 1, the ten bulbs from the picture, 99 and 100 on either side of a square, and Integer.MAX_VALUE. Then it compares bulbSwitch with simulate for every n from 0 to 2000.

Java
public class BulbSwitcher {

    public static int bulbSwitch(int n) {
        return (int) Math.sqrt(n);    // the squares 1, 4, 9, ... up to n
    }

    // The slow way, used only to check the answer: flip the bulbs round by round.
    static int simulate(int n) {
        boolean[] on = new boolean[n + 1];        // on[b] is bulb b, from 1 to n
        for (int round = 1; round <= n; round++) {
            for (int b = round; b <= n; b += round) {
                on[b] = !on[b];
            }
        }
        int count = 0;
        for (int b = 1; b <= n; b++) {
            if (on[b]) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] tests = {3, 0, 1, 10, 99, 100, Integer.MAX_VALUE};
        for (int n : tests) {
            System.out.println("bulbSwitch(" + n + ") = " + bulbSwitch(n));
        }
        boolean same = true;
        for (int n = 0; n <= 2000; n++) {
            same &= bulbSwitch(n) == simulate(n);
        }
        System.out.println("same as simulating every round, n = 0 to 2000: " + same);
    }
}

Running it prints:

Output
bulbSwitch(3) = 1
bulbSwitch(0) = 0
bulbSwitch(1) = 1
bulbSwitch(10) = 3
bulbSwitch(99) = 9
bulbSwitch(100) = 10
bulbSwitch(2147483647) = 46340
same as simulating every round, n = 0 to 2000: true

The line bulbSwitch(10) = 3 matches the three orange columns in the picture, and bulbSwitch(0) = 0 shows that a row of no bulbs needs no special case. Compare bulbSwitch(99) = 9 with the line after it: 100 is 10 × 10, so bulb 100 is the tenth perfect square, while 99 only reaches 9 × 9 = 81.

For n = 2,147,483,647 the method prints 46340, the largest whole number whose square fits in an int, and nothing wraps around because nothing is multiplied. The last line shows that the one-line formula and the round-by-round simulation agree on all 2,001 values of n from 0 to 2000.

Complexity

The method does one square root and one cast, however many bulbs there are.

  • Time: O(1), because the answer comes from a single Math.sqrt call and a cast, with no loop over the bulbs or the rounds.
  • Space: O(1), because no array of bulbs is built and the method keeps nothing but the root it computes.

Stepping through every r-th number, as the rounds do here, is also how the sieve in Count Primes crosses out multiples.