Summary of php implementation of Joseph's Problem
This article mainly introduces the php method for implementing Joseph's problem. The example summarizes two common techniques for implementing Joseph's problem, which has some reference value. For more information, see
This example summarizes the php implementation of Joseph's problem. Share it with you for your reference. The specific analysis is as follows:
A group of monkeys are arranged in a circle and numbered by 1, 2,... and n. Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ..., the monkey is called the King until there is only one monkey. Programming to simulate this process, input m, n, and output the number of the last king.
Resolution:
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:
?
1 2 3 4 5 6 7 8 9 10 11 |
<? Php Function getLeader ($ n, $ m ){ $ Res = 0; For ($ I = 2; $ I <= $ n; $ I ++ ){ $ Res = ($ res + $ m) % $ I; } Return $ res + 1; } $ Leader = getLeader (13, 34 ); Echo $ leader; ?> |
Method 2:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<? Php // Define a function Function getKing ($ monkeys, $ m, $ current = 0 ){ $ Number = count ($ monkeys ); $ Num = 1; If (count ($ monkeys) = 1 ){ Echo '<font color = "red"> the monkey numbered'. $ monkeys [0]. 'becomes the Monkey King! </Font> '; Return; } Else { While ($ num ++ <$ m ){ $ Current ++; $ Current = $ current % $ number; } The monkey with echo ". $ monkeys [$ current]." was kicked out... <br/> "; Array_splice ($ monkeys, $ current, 1 ); GetKing ($ monkeys, $ m, $ current ); } } $ N = 13; // total number of monkeys $ M = 34; // The number of monkeys to be kicked out $ Monkeys = range (1, $ n); // Add the Monkey number to the array. GetKing ($ monkeys, $ m); // call a function ?> |
I hope this article will help you with php programming.