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 <iostream> # include <list> using namespace STD; int lastnumber (unsigned int N, unsigned int m) {If (n <1 | M <1) return-1; List <int> lnum; int I = 0; for (I = 0; I <n; I ++) {lnum. push_back (I) ;}list <int >:: 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 <m; I ++) {cur ++; If (lnum. end () = cur) {cur = lnum. begin () ;}list <int >:: iterator next =++ cur; If (next = lnum. end () Next = lnum. begin (); cout <* (-- cur); lnum. erase (cur); cur = next;} return * cur;} int main () {cout <Endl <lastnumber (5, 3); Return 0 ;}
Running result:
2. Use a circular linked list
# Include <iostream> # include <list> 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 = PHE Ad;} void deletenum (plist & phead, unsigned 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 <Endl <p-> data <Endl;} void print (plist & phead) {plist P = phead; do {cout <p-> data <"; P = p-> pnext;} while (P! = Phead);} int main () {plist head = NULL; createlist (Head, 5, 3); cout <"original linked list:"; print (head ); cout <Endl <"in sequence:" <Endl; deletenum (Head, 3); // print (head); Return 0 ;}
The running result is:
3. Use recursion to find the rule
# Include <iostream> # include <list> 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 (S-1, n) + n) % m;} int main () {cout <lastnum (5, 3); cout <lastremainnum (5, 3); Return 0 ;}
Running result: