A group of monkeys in a circle, according to 1,2,...,n sequentially numbered. And then, starting with the 1th, count to the number of M, and kick It out of the loop.

Source: Internet
Author: User

A group of monkeys in a circle, according to 1,2,...,n sequentially numbered. Then, starting from the 1th, Count to M., Kick It Out of the loop, start counting from behind it, Count to M., and Kick It out ... and so on, until the last monkey is left, the monkey is called the King. Requires programming to simulate this process, enter m, N, output the last king's number

<?php

$n the number of monkeys $m the first few places

function fn ($n, $m)
{

Put the number of monkeys in the array
for ($i = 1; $i < $n +1; $i + +) {
$arr [] = $i;
}
$i = 0;
Var_dump ($i);

When only one value is left in the array to jump out of the array
while (count ($arr) > 1) {
echo $i. " \ n ";
if (($i + 1)% $m = = 0) {

When the number of cycles satisfies the M value to remove the current value
Unset ($arr [$i]);
}else{

Do not meet the number of loops put into the array to the tail
Array_push ($arr, $arr [$i]);

Delete Current loop contents
Unset ($arr [$i]);
}
$i + +;
}
return $arr;
}

Var_dump (FN (15,7));

A group of monkeys in a circle, according to 1,2,...,n sequentially numbered. And then, starting with the 1th, count to the number of M, and kick It out of the loop.

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.