PHP练习-约瑟夫环问题

2018-08-22 15:00 By "Powerless" 2840 0 1

一群猴子排成一圈,按1,2,...,n依次编号。然后从第1只开始数,数到第m只,把它踢出圈,从它后面再开始数,再数到第m只,在把它踢出去...,如此不停的进行下去,直到最后只剩下一只猴子为止,那只猴子就叫做大王。要求编程模拟此过程,输入m、n,输出最后那个大王的编号。

function monkey($m,$n){
    for($i=1;$i<$m+1;$i++){
        $arr[]=$i;
    }
    $i=0;
    while(count($arr)>1){
        if(($i+1)%$n==0){
            unset($arr[$i]);
        }else{
            array_push($arr,$arr[$i]);
            unset($arr[$i]);
        }
        $i++;
    }
    return $arr[$i];
}
echo "猴子大王的编号是".intval((monkey(6,8)));


评 论

View in WeChat

Others Discussion

  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 让你的PHP7更快(GCC PGO)
    Posted on 2018-03-07 14:09
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • BASE原则
    Posted on 2020-12-17 16:42