light problem

There are n lamps, numbered from 1 to n. Person 1 turns all lights on, Person 2 presses all switches numbered in multiples of 2 (the lights will be turned off), Person 3 presses all switches numbered in multiples of 3 (where the off lights will be turned off) is turned on, lights that are on will be turned off), and so on. There are k people in total. Which lights are on at the end? 
Input
n and k, 1≤k≤n≤1000. 
Output
outputs the number of lights that are on. 
Sample Input
7 3
Sample Output

1 5 6 7


The first thing to solve is: how to represent the state of the light, the method is to store the state of each light in an integer array named a, a[i]=0 means the light is off, a[i]=1 means the light is on .

                                    How to change the state of the light. Every time a person comes in, it is necessary to traverse all the lights in the classroom. If it is a multiple of the student's number, press the switch once, otherwise, the state will not be changed. It is easy to think of using conditional statements to solve problems.

                                   Because every time I come in, I think that the students have to traverse the lights, so the number of traversals is determined by the number of students who come in. Because in the loop, the number of classmates is in the outer layer, and the number of lamps is in the inner layer.

When making changes to the state of the light bulb, intentionally very detailed problems

                                                                                 1. First, set all the bulbs to off state, that is to say, assign 0 to all the completions in the a array, memset(a,0,sizeof(a));

                                                                                 2. When modifying the lights layer by layer, it should be noted that when a[ 10 ]=0, it means that the 11th lamp is off .

                                                                                 3. When modifying the state of the i-th lamp repeatedly, a[i-1]=(a[i-1]+1)%2;

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define MAXN 1000+10
int a[MAXN];
int main(){
    int i,j,x,n,k;
    cin>>n>>k;
    memset(a,0,sizeof(a));
    for(j=1;j<=k;j++){
                      for(i=1;i<=n;i++){
                                       if(i%j==0)a[i-1]=(a[i-1]+1)%2;
                                       }
                      }
    for(i=1;i<=n;i++){
                      if(a[i-1])cout<<i;
                      }
    system("pause");
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684974&siteId=291194637