#T374. 开关灯问题加强版
开关灯问题加强版
Description
Suppose there are N lights (where N is a positive integer not greater than 5000), numbered sequentially from 1 to N, all initially in the "on" state. There are also M people (where M is a positive integer not greater than N), numbered sequentially from 1 to M.
The first person (number 1) turns off all the lights. The second person (number 2) turns on all lights with numbers that are multiples of 2. The third person (number 3) toggles the state of all lights with numbers that are multiples of 3 (i.e., turns off lights that are on and turns on lights that are off). Following the order of increasing numbers, each subsequent person behaves like the third person, toggling the state of all lights whose numbers are multiples of their own number.
The question is: After the M-th person has performed their operation, which lights are in the "off" state? Output their numbers in ascending order, separated by commas.
Input Format
Input the positive integers N and M, separated by a single space.
Output Format
Output the numbers of the lights that are off in order, separated by English commas (,).
n, m = map(int, input().split())
lights = [True] * (n + 1) # True means on, False means off
for person in range(1, m + 1):
if person == 1:
for i in range(1, n + 1):
lights[i] = False
elif person == 2:
for i in range(2, n + 1, 2):
lights[i] = True
else:
for i in range(person, n + 1, person):
lights[i] = not lights[i]
off_lights = [str(i) for i in range(1, n + 1) if not lights[i]]
print(','.join(off_lights))
10 10 、
1,4,9
Hint
Watch out for pitfalls.
Source
CodesOnline