The linked list solution and mathematical solution of Joseph Ring related problems (PHP)

Source: Internet
Author: User
The chain list solution and mathematical solution of Joseph Ring problem (PHP)

Joseph Ring Question

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, and output the number of the last king.

Chain List Solution

function king($n,$m){    $monky = range(1,$n);    $i = 0;    while(count($monky)>1){        $i+=1;        $head = array_shift($monky);        if($i%$m!=0){            array_push($monky,$head);        }    }    return $monky[0];}echo king(10,3);

Mathematical Solutions

  • X ' = 2 3 4 5 0
  • x = 0 1 2 3 4
  • X ' = (x+m)%n

    function king2($n,$m){    $r = 0;    for($i=2;$i<=$n;$i++){        $r = ($r+$m)%$i;    }    return $r+1;}echo king2(10,3);

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

  • 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.