Problem description: N monkeys are sitting in a circle and numbered from 1 to n clockwise. Then, the number of monkeys started to report data from 1 clockwise and reported to M's monkeys for exit. Then, the number of monkeys started to report data again from the next position of the first monkey, it is king.
Here we use a recursive formula:
- F [I] = (F [I-1] + M) % I> = 2
F [I] indicates that when I have a monkey, M monkeys are removed each time, and the coordinates of the King (starting from 0) are the coordinates of only one monkey. The coordinates of the King are 0, recurrence to obtain the coordinates of the king when I was a monkey.
1 <HTML> 2 <body> 3 <? PHP 4 function monkeyking ($ N, $ m) {// $ n indicates the total number of monkeys, and $ M indicates that the monkey step size is 5 $ S = 0. // $ s indicates the King coordinate, when there is only one monkey, the coordinates of the King are 0 6 for ($ I = 2; $ I <= $ N; $ I ++) {// recursive in turn, A total of $ n monkeys are expected. If the step size is $ m, the king's coordinates 7 $ S = ($ S + $ m) % $ I; // return $ s; 10} 11 12 echo monkeyking (6, 2); 13?> 14 </body> 15
Page output
4