N, M = map(int, input(">>>").split())
CODE = [False if _ % 2 != 0 else True for _ in range(N + 1)]
for i in range(3, M + 1):
for j in range(i, N + 1, i):
CODE[j] = not CODE[j]
res = ','.join(str(i) for i, j in enumerate(CODE[1:]) if j == False)
print(res)
用c++就不会超时了
>>> import numpy as np
>>> import time
>>> def func(n, m):
t0 = time.time()
lamps = np.empty(n)
index = np.arange(n, dtype=np.int32)
lamps.fill(0) # 第1个人关闭所有的灯
for i in range(2, m+1): # 从第2个人开始,翻转灯编号能被自己编号整除的灯
lamps[index%i==(i-1)] += 1
result = np.where(lamps%2==0)[0] # lamps%2==0表示关闭的灯
t1 = time.time()
print('最终有%d盏灯是关闭的'%result.shape[0])
print('耗时:%d毫秒'%(1000*(t1-t0)))
>>> func(5000, 100)
最终有2332盏灯是关闭的
耗时:5毫秒
>>> func(5000, 199)
最终有2522盏灯是关闭的
耗时:6毫秒
>>> func(5000, 999)
最终有2601盏灯是关闭的
耗时:31毫秒