Three methods to solve the Joseph Ring Problem
Joseph's ring is an application of mathematics: n people (represented by numbers 1, 2, 3... n) are known to be sitting around a round table. The number of people numbered k starts to report, and the person counting m is listed; the next person reporting the number from 1, and the person counting m is listed again; repeat this rule, until all the people around the Round Table are listed.
Method 1: Use stl: list to simulate a circular linked list. Refer to offoffoffoffer
Code:
# Include
# Include
Using namespace std; int lastNumber (unsigned int n, unsigned int m) {if (n <1 | m <1) return-1; list
LNum; int I = 0; for (I = 0; I <n; I ++) {lNum. push_back (I);} list
: Iterator cur = lNum. begin (); while (lNum. size ()> 1) {// each time it is the I start value, m value for a long time, this time remember for (I = 1; I
: Iterator next = ++ cur; if (next = lNum. end () next = lNum. begin (); cout <* (-- cur); lNum. erase (cur); cur = next;} return * cur;} int main () {cout <
Running result:
2. Use a circular linked list
# Include
# Include
Using namespace std; typedef struct list {int data; struct list * pNext;} List, * pList; void createList (pList & pHead, unsigned int m, unsigned int n) {if (m <1 | n <1) return; pList p = pHead, q; bool isFirst = true; for (int I = 0; I <m; I ++) {q = (pList) malloc (sizeof (List); q-> data = I; q-> pNext = NULL; if (isFirst) {p = pHead = q; isFirst = false;} else {p-> pNext = q; p = q ;}} q-> pNext = pHead ;} void deleteNum (pList & pHead, un Signed int n) {pList p = pHead, q; int I = 0; while (p-> pNext! = P) {for (I = 1; I <n; I ++) {p = p-> pNext;} cout <p-> data <""; q = p-> pNext; p-> data = p-> pNext-> data; p-> pNext = p-> pNext; free (q );} cout <
Data <
Data <"; p = p-> pNext;} while (p! = PHead);} int main () {pList head = NULL; createList (head, 5, 3); cout <"original linked list:"; print (head ); cout <
The running result is:
3. Use recursion to find the rule
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
VcD4KPHByZSBjbGFzcz0 = "brush: java;"> # include
# Include
Using namespace std; // use the for loop to solve int lastRemainNum (unsigned int m, unsigned int n) {if (m <1 | n <1) return-1; int last = 0; for (int I = 2; I <= m; I ++) {last = (last + n) % I; // cout <last <";}return last ;}// use recursive int lastNum (unsigned int m, unsigned int n) {if (m <1 | n <1) return-1; if (m = 1) return 0; return (lastNum (m-1, n) + n) % m;} int main () {cout <lastNum (5, 3); cout <lastRemainNum (5, 3); return 0 ;}
Running result: