C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > 约瑟夫环

约瑟夫环问题(数组法)c语言实现

投稿:shangke

这篇文章主要介绍了约瑟夫环问题(数组法)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;
}

阅读全文