public static void main(String[] args) { int[] all = new int[500]; for (int i = 0; i < 500; i++) { all[i] = i + 1; } while (all.length >= 3) { int length = all.length; int j = 0; for (int i = 0; i < length; i++) { if ((i + 1) % 3 == 0) { all[i] = 0; } else { j++; } } int[] newary = new int[j]; int a = 0; for (int i = 0; i < length; i++) { if (all[i] != 0) { newary[a++] = all[i]; } } all = new int[j]; all = newary; } for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } }
典型的约瑟夫环问题。最普通的方式就是模拟整个过程,建立boolean数组,true表示此人已出列,false表示此人还在圈子中。模拟整个过程。时间复杂度为(3*500)(如果不懂可以再追问)用数学方法得到递推公式:F(i) = ( F(500-1)+3 )%500public class ProgramTest {
public static void main(String[] args) {
final int N =500;
final int M =3;
int result =0;
for(int i=2;i<=N;++i){
result = (result+M)%i
}
System.out.print(result);
}
}