网络上有一种是发现打开门的规律,然后用数学的方法来解决的,但是一般发现比较困难。
所以用了模拟的方法模拟器过程,用数组代表门的状态。
package test; import java.util.Scanner; //使用数组记录门的开关状态,最终统计数组中的0的个数就是打开的门的个数 public class test { public static void main(String args[]) { Scanner cin = new Scanner(System.in); int count = cin.nextInt(); while (count > 0) { int n = cin.nextInt(); int[] situ = new int[101]; for (int i = 0; i < 101; i++) situ[i] = 1; int round = 1; for (int i = 1; i <= n; i++) {// 进行n轮的喝酒,开门/关门 for (int j = round; j <= n; j += round) {//第round轮的时候,访问的门号每次增大round if (situ[j] == 1) situ[j] = 0; else situ[j] = 1; } round++; } int sum = 0; for (int j = 1; j <= n; j++) { if (situ[j] == 0) sum++; } System.out.println(sum); count--; } } }