hdu_problem_2053_Switch Game

题目大意为:有一排全部都是关着的灯,然后在这些灯上进行了一系列的操作,第i次操作时将i的倍数的灯改变状态,即ON变成OFF,OFF变成ON,输入n,输出再无数次操作后,第n盏灯的状态,0表示OFF,1表示ON

思路:从数字本身的性质考虑
1)如果一个数是质数,那么它只能分解为1和它本身,也就是只会执行2次操作,那么如果是质数,肯定是关闭的状态。
2)如果一个数是合数,就要分两个情况

  1. 如果它不是完全平方数,那根据合数的定义,肯定可以分解成n个组合,每个组合里面都是2个不相等的数字,例如6=16=236 = 1*6 = 2*3,也就是说这个数经历了偶数次操作,那么肯定也是关闭状态。
  2. 如果这个数是完全平方数,那么他可以分解为n-1个组合加上他的算术平方根,例如4=14=224 = 1*4=2*2,这种情况下,这个数字只被操作了奇数次,那么这个灯的状态就是开着的。

综上所述,如果这个数是完全平方数(肯定不是质数),就是ON,如果不是,就是OFF

/*
*
*Problem Description
*There are many lamps in a line. All of them are off at first. A series of operations are carried out on these lamps. On the i-th operation, the lamps whose numbers are the multiple of i change the condition ( on to off and off to on ).
*
*
*Input
*Each test case contains only a number n ( 0< n<= 10^5) in a line.
*
*
*Output
*Output the condition of the n-th lamp after infinity operations ( 0 - off, 1 - on ).
*
*
*Sample Input
*1
*5
*
*
*Sample Output
*1
*0
*
*Hint
*hint
*
*
*Consider the second test case:
*
*The initial condition    : 0 0 0 0 0 …
*After the first operation  : 1 1 1 1 1 …
*After the second operation : 1 0 1 0 1 …
*After the third operation  : 1 0 0 0 1 …
*After the fourth operation : 1 0 0 1 1 …
*After the fifth operation  : 1 0 0 1 0 …
*
*The later operations cannot change the condition of the fifth lamp any more. So the answer is 0.
*
*
*Author
*LL
*
*
*Source
*校庆杯Warm Up
*
*
*Recommend
*linle
*
*/
#include<iostream>
using namespace std;
int i;
bool is_on(int n) {
 i = sqrt(n);
 return i * i == n;
}
float sqrt(int num) {
 float temp;
 for (temp = 0; temp*temp <= num; temp += 1);
 temp -= 1;
 for (int i = 0; i < 3; i++) {
  temp = (temp + num / temp) / 2;
 }
 return temp;
}
int main() {
 int n;
 while (cin >> n) {
  if (is_on(n))
   cout << "1" << endl;
  else
   cout << "0" << endl;
 }
 system("pause");
 return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章