约瑟夫环问题(数组法)c语言实现
有N个编号为1~N的人围成一圈,现在每隔两个人(比如:1、4 之间隔了2、3)就将一个人淘汰出去,问最后剩下的是编号为几的人?
算法代码如下
#include <stdio.h>
#include <stdlib.h>
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\n");
}
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\n", peoples[i]);
peoples[i] = 0;
rest--;
}else if (rest==1){
printf("NO. %d is alive\n", peoples[i]);
rest--;
}
i++;
}
system("pause");
return 0;
}
最新评论