1. 程式人生 > >HDU 2053 Switch Game(開燈問題,唯一分解定理)

HDU 2053 Switch Game(開燈問題,唯一分解定理)

Switch Game

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15011    Accepted Submission(s): 9160


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 題意:有n盞燈,原來全部是關閉的,經過n次操作,問最後一盞燈的狀態.每次次數是燈的編號是,撥動燈的開關,(有可能開啟或者關閉).
思路:首先想到的是模擬,但是超時了,後來發現,n的狀態由n的約數個數決定,當約數個數為偶數是,n的狀態不變(關閉),當為奇數的時候發生改變(開啟).所以只要統計約數的個數便可解決問題. 小發現:當約數個數為奇數的時候,這個數一定為平方數!所以此問題就轉變為判斷一個數是不是平方數. 原理: 30的約數為: (1,30), (2,15), (3,10) 36的約數為: (1,36), (2,18), (3,12), (4,9), (6) 一個數的約數總是成對的出現,當為平方數的時候有兩個約數相同,就只算一個. PS:判斷平方數的方法速度更快!

AC程式碼1

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        double x=sqrt(n*1.0);
        cout<<(x==int(x))<<endl;

    }
    return 0;
}

AC程式碼2:

#include <iostream>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        int sum=0;
        for(int i=1; i<=n; i++)
        {
            if(n%i==0)
                sum++;
        }

        cout<<sum%2<<endl;

    }
    return 0;
}