约舍夫问题

 1 /*
 2 
 3 约舍夫问题:
 4 M个人围成圈,相邻相继编号1-M;
 5 从1号人开始1号报数;
 6 如果所报数为m,则撤出圆圈队伍。相邻的下一位报数者从1开始。
 7 直至剩下最后一位,求其是第几位。
 8 
 9 */
10 
11 # include<stdio.h>
12 
13 void main(){
14     int M = 0; int sum = 0; int m = 0;  int tmp = 0; int Num = 0;
15     printf("Input the number(<1000) of people:\n");
16     wscanf_s(L"%d", &M);
17     printf("Input the number that people would say:\n");
18     wscanf_s(L"%d", &m);
19     int k [1000];
20     for(int j = 0; j <1000; j++){
21         k[j] = 1;
22     }                                         //init k[]
23     while(Num!=M-1)
24     {
25       printf("The %d loop\n",m);
26 
27       for (int i = 0; i < M; i++){        
28         if (k[i] == 1)
29         {
30             sum++;
31             if (sum % m == 0)
32             {
33                 k[i] = 0; printf("Remove %d\n", i+1); Num++;           //The people that ID is i+1 remove.  add 1. 
34                 
35             }
36          }
37         if (Num == M-1)                                               //The rest of people is one. Out of the loop.
38             break;
39       }    
40     }
41     
42     for (int j = 0; j < M; j++){
43         if (k[j]==1)
44         printf("The last people ID is %d", j+1);
45 
46     }
47     system("pause");
48 }

 

posted @ 2014-10-25 23:21  UDLD  阅读(447)  评论(0编辑  收藏  举报