美文网首页
数组之关灯问题

数组之关灯问题

作者: waterOnTheMars | 来源:发表于2016-05-04 17:32 被阅读0次

    有n盏灯,编号为1~n。第1个人把所有灯打开,第二个人按下所有编号为2的倍数的开关(这些灯将被关掉),第3个人按下所有编号为3的倍数的开关。依此类推。一共有k人,问最后哪些灯开着?

    输入n和k,输出开着的灯的编号。
    样例输入:
    7 3
    输出:
    1 5 6 7
    #include <iostream>
    using namespace std;
    int main()
    {
    int a[7] = {1,1,1,1,1,1,1};
    //1st person
    for(int i = 2;i<=3;i++)
    {
    for(int j = 0;j<7;j = j + i)
    {
    a[j] = (a[j] == 0?1:0);
    }
    }
    for(int n = 0;n<=6;n++)
    {
    cout<<" "<<a[n]<<" ";
    }
    cout<<endl;
    return 0;
    }
    最后输出的数组,1代表开着,0代表关着
    github地址:
    https://github.com/will-I-amor/cppPrac/blob/master/light_turn_Mercury.cpp

    相关文章

      网友评论

          本文标题:数组之关灯问题

          本文链接:https://www.haomeiwen.com/subject/pkorrttx.html