319. Bulb Switcher

本文探讨了一个经典的灯泡开关问题,通过分析得出结论:只有位于平方数位置的灯泡最终会保持开启状态。文章详细解释了为何平方数位置的灯泡会有奇数个因数,而非平方数位置的灯泡则会有偶数个因数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

摘自

http://my.oschina.net/Tsybius2014/blog/599157

http://blog.youkuaiyun.com/ironyoung/article/details/50358843

http://bookshadow.com/weblog/2015/12/19/leetcode-bulb-switcher/

--------------------------------------------------------------------------------------------------------------------------------------

对于每个数字来说,除了平方数,都有偶数个因数。

如6有4个因数:1×6=6,2×3=6

如60有个因数:1×60=60,2×30=60,3×20=60,4×15=60,5×12=60,6×10=60

可以看出,非平方数的因数总是成对出现的,只有平方数的因数才是奇数,因为平方数除平方根外,其他的因数都是成对出现的!对于当前的开关灯泡问题,可知到最后处在平方数位置的灯泡一定是开启的,其他位置的灯泡一定是关闭的。而要计算一个数之下有多少小于或等于它的平方数,使用一个开平方用的函数就可以了。

--------------------------------------------------------------------------------------------------------------------------------------

我们知道,每当灯泡会改变状态,也就是 toggle 时,是因为它出现在了某个数的整数倍上。

对于第1个灯泡:1*1,会改变1次状态,即 off -》on

对于第2个灯泡:1*2,2*1,会改变2次状态,即 off -》on -》off

对于第3个灯泡:1*3,3*1,会改变2次状态,即 off -》on -》off

对于第4个灯泡:1*4,2*2,4*1,会改变3次状态,即 off -》on -》off -》on

……

会发现,每当我找到一个数的整数倍,总会找到对称的一个整数倍,例如 1*2,就肯定会有一个 2*1。唯一的例外出现在平方数上,例如 4 = 2*2,只有一次整数倍。

每次作为偶数次整数倍,最终的灯泡都会还原为 off;只有作为奇数次整数倍,最终的灯泡都会 on。

也就是说,最终亮的灯泡数目由小于其的最大平方数确定。


--------------------------------------------------------------------------------------------------------------------------------------

数学题,答案等于int(math.sqrt(n))

对于第i栈灯泡,当i的因子个数为奇数时,最终会保持点亮状态,例如9的因子为1,3,9
而当i的因子个数为偶数时,最终会保持熄灭状态,例如8的因子为:1,2,4,8
当且仅当i为完全平方数时,其因子个数为奇数

为什么只有完全平方数的因子个数为奇数呢?

因为除了完全平方数,其余数字的因子都是成对出现的,而完全平方数的平方根只会统计一次。

前10盏灯泡的开闭过程如下所示:

0 0 0 0 0 0 0 0 0 0    0
1 1 1 1 1 1 1 1 1 1    1
1 0 1 0 1 0 1 0 1 0    2
1 0 0 0 1 1 1 0 0 0    3
1 0 0 1 1 1 1 1 0 0    4
1 0 0 1 0 1 1 1 0 1    5
1 0 0 1 0 0 1 1 0 1    6
1 0 0 1 0 0 0 1 0 1    7
1 0 0 1 0 0 0 0 0 1    8
1 0 0 1 0 0 0 0 1 1    9
1 0 0 1 0 0 0 0 1 0    10

--------------------------------------------------------------------------------------------------------------------------------------


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值