Summary of php implementation of Joseph's problem, and php implementation of Joseph's summary. Php implementation of Joseph's problem method summary, php implementation of Joseph's summary this example summarizes the php implementation of Joseph's problem method. Share it with you for your reference. The specific analysis is as follows: a summary of php's methods for implementing Joseph's problem, and a summary of php's implementation of Joseph's problem
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:
<?phpfunction 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:
<? Php // define function getKing ($ monkeys, $ m, $ current = 0) {$ number = count ($ monkeys); $ num = 1; if (count ($ monkeys) = 1) {echo 'number is '. $ monkeys [0]. 'The monkey becomes the Monkey King! '; Return;} else {while ($ num ++ <$ m) {$ current ++; $ current = $ current % $ number;} echo "no ". $ monkeys [$ current]. "The monkey was kicked out...
"; Array_splice ($ monkeys, $ current, 1); getKing ($ monkeys, $ m, $ current) ;}}$ n = 13; // total number of monkeys $ m = 34; // The number of monkeys to which the number is reached is kicked out $ monkeys = range (1, $ n ); // put the monkey number into the array getKing ($ monkeys, $ m); // call the function?>
I hope this article will help you with php programming.
Examples in this article summarize how php implements Joseph's problem. Share it with you for your reference. The specific analysis is as follows: 1...