Bulb Switcher - Problem
The Great Bulb Switching Challenge!
Imagine you have
๐ด Round 1: Turn on ALL bulbs (every 1st bulb)
๐ก Round 2: Toggle every 2nd bulb (positions 2, 4, 6, ...)
๐ข Round 3: Toggle every 3rd bulb (positions 3, 6, 9, ...)
โญ Round i: Toggle every i-th bulb
๐ฏ Round n: Toggle only the last bulb
After completing all
Note: "Toggle" means switching the state - if a bulb is ON, turn it OFF, and if it's OFF, turn it ON.
Imagine you have
n light bulbs arranged in a row, all initially turned off. You're about to perform a fascinating switching ritual:๐ด Round 1: Turn on ALL bulbs (every 1st bulb)
๐ก Round 2: Toggle every 2nd bulb (positions 2, 4, 6, ...)
๐ข Round 3: Toggle every 3rd bulb (positions 3, 6, 9, ...)
โญ Round i: Toggle every i-th bulb
๐ฏ Round n: Toggle only the last bulb
After completing all
n rounds, your task is to count how many bulbs are still ON.Note: "Toggle" means switching the state - if a bulb is ON, turn it OFF, and if it's OFF, turn it ON.
Input & Output
example_1.py โ Small Case
$
Input:
n = 3
โบ
Output:
1
๐ก Note:
Initially [OFF,OFF,OFF]. Round 1: toggle all โ [ON,ON,ON]. Round 2: toggle every 2nd โ [ON,OFF,ON]. Round 3: toggle every 3rd โ [ON,OFF,OFF]. Only bulb 1 (position 1) remains ON. Result: 1
example_2.py โ Medium Case
$
Input:
n = 6
โบ
Output:
2
๐ก Note:
After all rounds, only bulbs at positions 1 and 4 remain ON. These are perfect squares (1ยฒ = 1, 2ยฒ = 4). Perfect squares โค 6: {1, 4}. Count = 2
example_3.py โ Edge Case
$
Input:
n = 0
โบ
Output:
0
๐ก Note:
No bulbs means no bulbs can be ON. Result: 0
Visualization
Tap to expand
Understanding the Visualization
1
Divisor Insight
Each bulb i gets toggled once for every divisor of i
2
Pairing Pattern
Divisors usually come in pairs (d, n/d), giving even counts
3
Special Case
Perfect squares have one divisor (โn) that pairs with itself
4
Final State
Only odd toggle counts (perfect squares) remain ON
Key Takeaway
๐ฏ Key Insight: Only perfect squares have an odd number of divisors, so only they remain ON after all switching rounds!
Time & Space Complexity
Time Complexity
O(1)
Just computing the square root of n, which is a constant time operation
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to store the result
โ Linear Space
Constraints
- 0 โค n โค 109
- Large inputs require O(1) solution
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code