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:
思路:就是判断1-n中因式分解因式的个数为奇数的个数。素数为2,一般的合数也是偶数个,只有有两个相同因式的数为奇数,即某个数的平方。
class Solution {
public:
int bulbSwitch(int n) {
//就是判断每个数因式分解的个数
// 质数只有1和他本身,所以最后为off
//合数要想总的因数为奇数,那么肯定有两个因式一样,即这个数肯定是某个数的平方
//所以本体就是求k^2<=n中k的个数
return sqrt(n);
}
};