23. lights problem

topic:

N-lamp, numbered 1 ~ n. Person 1 all the lights on, the second number is a multiple of all the individual pressing switches 2 (the lamps are turned off), the third number is a multiple of all individual press switch 3, and so on. A total of k individual, and finally asked what the lights are on. N inputs and k, the number of output driving a lamp. k <= n <= 1000.

Sample input:

7  3

Sample output:

1  5  6  7

 

Ideas:

It represents an array of type int lamps. The array is initialized to -1, this closed state. Analyzing sequence, the final output value of the beacon 1.

 

Code:

#include <iostream>
using namespace std;

int main()
{
int n = 0, k = 0;
cin >> n >> k;
int *light = new int[n + 1];

for (int i = 1; i < n + 1; ++i) {
light[i] = -1;
}

for (int i = 1; i <= k; ++i) {
for (int j = 1; j < n + 1; ++j) {
if (j % i == 0) {
light[j] = -light[j];
}
}
}

for (int i = 1; i < n + 1; ++i) {
if (light[i] == 1) {
cout << i << " ";
}
}

return 0;
}

Guess you like

Origin www.cnblogs.com/Hello-Nolan/p/12128006.html