Bulb Switcher - Problem

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 i-th round, you toggle every i-th bulb.

For the n-th round, you only toggle the last bulb.

Return the number of bulbs that are on after n rounds.

Input & Output

Example 1 — Small Case
$ Input: n = 3
Output: 1
💡 Note: Initial: [OFF,OFF,OFF]. Round 1: [ON,ON,ON]. Round 2: [ON,OFF,ON]. Round 3: [ON,OFF,OFF]. Only bulb 1 stays on.
Example 2 — Perfect Square
$ Input: n = 9
Output: 3
💡 Note: Perfect squares 1, 4, 9 have odd number of divisors, so they remain on after all toggles.
Example 3 — Edge Case
$ Input: n = 0
Output: 0
💡 Note: No bulbs means 0 bulbs are on.

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Bulb Switcher Problem OverviewInput: n = 44 bulbs initially OFFRound 1: Toggle all → all ONRound 2: Toggle every 2nd → [ON,OFF,ON,OFF]Output: 21234Bulbs 1&4 are ON (perfect squares)Key Pattern DiscoveryBulb i gets toggled by each of its divisorsOnly perfect squares have ODD number of divisors → stay ONSolution: Count perfect squares ≤ n = floor(√n)
Understanding the Visualization
1
Input
Number of bulbs n
2
Process
Toggle bulbs in n rounds
3
Output
Count bulbs that are ON
Key Takeaway
🎯 Key Insight: Only perfect squares remain on because they have an odd number of divisors
Asked in
Google 25 Microsoft 20 Apple 15
38.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen