Joseph's ring (array method)
The problem indicates that this problem was named by Flavio Joseph, a Jewish historian of the 1st century. He wrote in his diary that he and his 40 comrades-in-arms were surrounded by the Roman army in the cave. They decided to commit suicide and decide who to kill by drawing lots. Joseph and the other are the last two people left behind. Joseph convinced the man that they would surrender to the Roman army and stop committing suicide. Joseph owes his survival to luck or God. He does not know which witty Joseph is!
There are N numbers 1 ~ N people are in a circle. Now, every two people (for example, 2 and 3 at the interval of 1 and 4) will be eliminated. What is the number of people in the end?
The algorithm code is as follows:
#include
#include
int main(void){ int people_count = 0; int *peoples = NULL; printf(please input people number: ); scanf(%d, &people_count); if (people_count < 2){ printf(can't do Joseph); } peoples = (int *)calloc(people_count, sizeof(int)); int i; for(i = 0; i < people_count; i++){ peoples[i] = i+1; } i = 0; int j = 0; int rest = people_count; while(rest){ if (i >= people_count){ i %= people_count; } if (peoples[i] == 0){ i++; continue; } if (j++ % 3 ==0 && rest > 1){ printf(kill people NO. %d, peoples[i]); peoples[i] = 0; rest--; }else if (rest==1){ printf(NO. %d is alive, peoples[i]); rest--; } i++; } system(pause); return 0;}