题目:
古代某法官要判决n个犯人死刑,他有一条荒唐的逻辑,将犯人首尾的相接排成圆圈,然后从第s个人开始数起,每数到第m个犯人,就拉出来处决;然后又数m个,数到的犯人又拉出来处决,依次类推。剩下的最后一人可以豁免。
自己智商能理解的写法
public class Josephus {
public static void main(String[] args) {
//编号从 0 到 n-1
//最终输出 最后一个活下来的人的编号
int n = 5; // 总人数
int s = 0; // 起始的人的编号
int d = 3; // 每数到第几个人
int alive_person = n;
int[] person_state = new int[n];
int current_person_index = s;
int counter = 0;
while( true ) {
// count
counter++;
// judge current person
if ( counter==d ) {
person_state[current_person_index] = 1; // kill this person
System.out.println("the person whose index is " + current_person_index+" die");
alive_person--;
counter = 0; // reset counter
}
// should we stop ?
if( alive_person == 1 ) {
for(int j=0; j<n; j++) {
if (person_state[j] == 0) {
System.out.println("The lucky person`s index is " + j);
}
}
return;
}
// go to next alive person
while(true) {
// move to next person (alive or dead)
current_person_index++;
if(current_person_index == n) {
current_person_index = 0;
}
// break when this person is alive
if( 0 == person_state[current_person_index] ) {
break;
}
}
}
}
}
从网上找的以自己智商看不懂的写法
int Joseph(int n, int m)
{
int fn=0;
for (int i=2; i<=n; i++)
{
fn = (fn+m)%i;
}
return fn;
}
public int Joseph(int n, int m) {
if(n == 1) return n;
return (Joseph(n - 1, m) + m - 1) % n + 1;
}
来源:CSDN
作者:Rabbit_Gray
链接:https://blog.csdn.net/Rabbit_Gray/article/details/104516779