问题:
有编号从1到N的N个人坐成一圈报数,报到M的人出局,下一位再从1开始,如此持续,直止剩下一位为止,报告此人的编号X。输入N,M,求出X。
源程序如下:
/**
* @author rmouse
* 2006-2-18
*
* 约瑟夫环问题
*
*/
public class Josephus {
public static void main(String args[]) {
int n =Integer.parseInt(args[0]) ;
int m =Integer.parseInt(args[1]) ;
int j;
int jj;
int jjj;
int jjjj;
int jjjjj;
int k;
int a[] = new int[n];
int b[] = new int[n];
for (jjj = 0; jjj < n; jjj++) {
a[jjj] = jjj + 1;
}
for (int i = n; i > 1; i--) {
k = m % i;
for (j = 0; j < (i - 1) && k < i; j++, k++) {
b[j] = a[k];
}
for (jj = j, k = 0; jj < i && k < (m % i - 1); jj++, k++) {
b[jj] = a[k];
}
for (jjjjj = 0; jjjjj < n; jjjjj++) {
a[jjjjj] = b[jjjjj];
b[jjjjj] = 0;
}
}
for (jjjj = 0; jjjj < n; jjjj++) {
if (a[jjjj] != 0) {
System.out.println(a[jjjj]);
}
}
}
}