PHP monkey election

Source: Internet
Author: User

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] = 0 I = 1
  • 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

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.