开关灯2
java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
ArrayList<Integer> result = findClosedLamps(N);
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
}
private static ArrayList<Integer> findClosedLamps(int N) {
ArrayList<Integer> closedLamps = new ArrayList<>();
// 初始化数组,全部设置为 true 表示灯都是开着的
boolean[] lamps = new boolean[N + 1];
// 开关灯操作
for (int i = 2; i <= N; i++) {
for (int j = i; j <= N; j += i) {
lamps[j] = !lamps[j];
}
}
// 找到关闭的灯的编号
for (int i = 1; i <= N; i++) {
if (!lamps[i]) {
closedLamps.add(i);
}
}
return closedLamps;
}
}