Description: Joseph problem: There are n monkeys, in the clockwise direction of a circle King (numbering from 1 to N), from the beginning of the 1th number, counting to M, the number of the monkey out of the circle, the rest of the monkeys continue to count from 1 onwards. In this way, until there is only one monkey in the circle, this monkey is the Monkey King, programming for input n,m, output the last Monkey King number.
Input: Each line is two integers separated by a space, the first is N, the second is m (0 < M, n < 300). The last line is: 0 0
Output: For each line of input data (except the last line), the output data is also a line, that is, the last monkey's number
Input
6 2
12 4
8 3
0 0
Output
5
1
7
Analysis: Monkeys can be represented by an array, the value of the array is the number of the monkey, when a monkey out of the code to change the number to 0
Indicating that the monkey was out of the game, when the last one left is a value not 0, the value is the monkey number.
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6 intN, M;7 inta[ -];8 while(Cin >> n >> m) &&! (n = =0&& m = =0))9 {Ten for(inti =0; I < n; i++) OneA[i] = i +1; A intk = n;//mark the rest of the monkeys - intj =0;//tagged m - while(k>1) the { - - for(inti =0; I < n; i++) - { + if(A[i] = =0) - Continue; + Else AJ + +; at if(j = m)//the monkey number out of the ring becomes 0. - { -A[i] =0; j =0; k--; - } - } - } in for(inti =0; I < n; i++) - { to if(A[i]! =0) +cout << A[i] <<Endl; - } the } *System"Pause"); $ return 0;Panax Notoginseng}
Joseph Problem (c + + implementation)