C语言——著名的Josephus问题练习

来源:互联网 发布:魔兽数据库7.0 编辑:程序博客网 时间:2024/06/16 02:57

Josephus(约瑟夫斯): 约37--100 ,犹太历史学家和军人.原名约瑟夫.本.马赛厄斯.生于耶路撒冷.西元66年在反对罗马的犹太起义中他指挥一支加利利军队.在向罗马人投降时他施展手段获取优待,得以前往罗马,在那里写出几部关于犹太历史和宗教的著作,包括《犹太战争史》(History of the Jewish War,西元75--79年问世)和《犹太古事记》(Antiquities of the Jews,西元93年问世)卒于罗马。

39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从,Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。

/*运行后输出结果为31.*/#include <stdio.h>#include <stdlib.h>#define N 41#define M 3typedef struct node *link;struct node {int item;link next;};link NODE(int item, link next){link t = malloc(sizeof *t);t->item = item;t->next = next;return t;}int main(){int i;link t = NODE(1, NULL); t->next = t;for (i=2; i<=N; i++)t = t->next = NODE(i, t->next);while (t != t->next) {for (i=1; i<M; i++) t = t->next;t->next = t->next->next;}printf("%d\n", t->item);return 0;}