# 约瑟夫排列（c/python)

2017-11-22 08:38:00来源:CSDN作者:qq_34637408人点击

### C代码

``#include<stdio.h>#include<stdlib.h>#define N 41int main(){    int man[N] = { 0 };    int count = 1;  //第count个自杀的人    int pos = 0;    int i = 0;    while (count <= N)    {        do        {            pos = pos % N;    //环状处理(如第pos=42时，42%41=1，即重回到索引为1的位置            if (man[pos] == 0)            {                i++;            }            if (i == 3)//数到三自杀            {                i = 0;                break;            }            pos++;        } while (1);        man[pos] = count;  //第i个位置表示第count自杀的人        count++;  //下一个自杀的人    }    printf("约瑟夫排列：/n");    for (int i = 0; i < N; i++)    {        printf("%d ", man[i]);    }    int num;    printf("/n请输入你想救的人数:");    scanf_s("%d", &num);    for (int i = 0; i < N; i++)    {        //1表示想救的人所在的位置        if (man[i] <= N - num)            printf("0 ");        else            printf("1 ");        if ((i+1) % 5 == 0)            printf("   ");    }    system("pause");    return０；}``

### python

``# -*- coding: utf-8 -*-"""Created on Tue Nov 21 19:48:05 2017@author: yangwenbin"""N=41def Josephus(man):    count=1    pos=0    i=0    while count<=N:        while 1:                 pos=pos%N  #环形处理            if man[pos]==0:                i=i+1                pass            if i==3:                i=0                break            pos+=1            pass        man[pos]=count        count+=1        pass    passif __name__=="__main__":    man=[0]*N    Josephus(man)    print(man)    num=input("请输入你想救的人数:")    for i in range(N):        if man[i]<=(N-int(num)):            print("0 ",end='')            pass        else:            print("1 ",end='')            pass        if (i+1)%5==0:            print("  ",end='')            pass        pass    pass``