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.
1 2 3 4 5 6 |
|
Solution
- 对于第i栈灯泡,当i的因子个数为奇数时,最终会保持点亮状态,例如9的因子为1,3,9
而当i的因子个数为偶数时,最终会保持熄灭状态,例如8的因子为:1,2,4,8 当且仅当i为完全平方数时,其因子个数为奇数 为什么只有完全平方数的因子个数为奇数呢?
因为除了完全平方数,其余数字的因子都是成对出现的,而完全平方数的平方根只会统计一次。
前10盏灯泡的开闭过程如下所示:
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 |
|