Middle-题目5:319. Bulb Switcher

来源:互联网 发布:nginx tomcat动静分离 编辑:程序博客网 时间:2024/05/12 12:57

题目原文:
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.
题目大意:
起初有n个灯泡,都是关闭的,你进行n轮操作:
第1轮,你把每个灯泡的状态都改变(打开的关闭,关闭的打开);
第2轮,你把每个灯泡序号是2的倍数的灯泡都改变状态(灯泡序号从1开始);
……
第i轮,你把每个灯泡序号是i的倍数的灯泡都改变状态(灯泡序号从1开始);
……
第n轮,你把最后一个灯泡改变状态(因为1~n里面n的倍数只有n)
求n轮过后,还有几个灯泡亮着?
题目分析:
若一个灯泡在n轮过后还是亮的,说明这个灯泡被改变了奇数次,因为只有被轮数整除的时候才能变状态,所以[1,k]能整除这个灯泡序号k的正整数是奇数个。
以下证明k是个完全平方数。
首先,若灯泡的序号i是平方数,则i的因数一定是奇数个,证明:
因为i是平方数,所以i=k*k,其中k∈Z,而1能整除i,所以i的因数个数为k的非1因子个数*2+1,一定是一个奇数。
那么若i不是平方数,i的因数必然是偶数个,证明:
设所有<i的因子构成的集合为A,>i的因子构成的集合为B,显然A∪B即为i的所有因子构成的集合,而对任意a∈A,必存在唯一的i/a∈B,反之亦然,所以A和B两个集合的元素个数相等。
综上证明,只有≤n的完全平方数最后是亮的。那么求i的取整即可。一行代码解决。
源码:(language : c)

int bulbSwitch(int n) {    return sqrt(n);}

成绩:
0ms,beats 6.36%,众数0ms,93.14%
Cmershen的碎碎念:
这道题起初只想到进行模拟,但看到discuss中给出的答案是求sqrt(n),遂想到了上述证明过程。

0 0
原创粉丝点击