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足够大,(i,j)表示灯泡在 第 i 个round时 第 j 次 被switch 状态
灯泡1: (1,1) ON
灯泡2: (1,2)(2,1)OFF
灯泡3: (1,2),(3,1)OFF
灯泡4: (1,4),(2,2),(4,1) ON
灯泡5: (1,5),(5,1)OFF
....................................................................................................
灯泡9: (1,9),(3,3),(9,1)ON
....................................................................................................
灯泡16:(1,16),(2,8),(4,4),(8,2),(16,1) ON
可以发现规律:
灯泡状态改变次数为奇数时,状态为ON,灯泡改变次数为偶数时,状态为OFF。并且第N个灯泡都是在满足 N = i * j 时状态改变。对于第16个灯泡有:
16 = 1 * 16
16 = 2 * 8
16 = 4 * 4
16 = 8 * 2
16 = 16 * 1
又发现 (1,16)与(16,1)抵消状态改变,(2,8)与(8,2)状态改变抵消,只在(4,4)时改变了一次使得状态为ON
第m(m <= N)个灯泡状态是否为ON,取决于m是否是完全平方数.
对于灯泡数N,亮灯的个数为小于等于N的完全平方数的个数,即根号N。如N = 16 ,根号16等于4,亮灯个数即为4,分别为第一个(1,1),第4个(2,2),第九个(3,3), 第16个(4,4)。
代码:
#include<iostream>
#include<math>
int main(){
int n;
cin>>n;
return sqrt(n);
}