【C】n個人排成一圈報數的問題

來源:互聯網
上載者:User

標籤:

問題來自:《C程式設計》(第四版)譚浩強 清華大學出版社 第291頁

有n個人圍城一圈,順序排號。從第一個人開始報數(從1報到m),凡是報到m的人退出圈子,接著從迴圈隊列的下一位開始報數(該數為1)。問最後留下的是原來幾號的那位。

註:本例為類比題,按要求寫程式即可。

範例程式碼:

 1 #include <stdio.h> 2  3 int a[100]; 4  5 int find(int *a, int n, int m) 6 { 7     int counter = n; 8     int i=0,j=0; 9     while(counter != 1) //還剩一人時跳出迴圈10     {11         for(j=1;j<=m;) //從1報數,報到了m12         {13             i = (i++)%n;14             if(a[i] != 0)15             {16                 j++;17             }18         }19         a[i] = 0;  //將報m的人踢出隊列20         counter--;  //計數器-121     }22     for(i=0;i<n;i++)23     {24         if(a[i] != 0)25             return i;   //返回唯一的剩餘者的位置26     }27 }28 29 30 //test31 int main()32 {33     int i;34     for(i=0;i<100;i++)35     {36         a[i] = i;37     }38     printf("%d",find(a,5,3));39     return 0;40 }

 

【C】n個人排成一圈報數的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.