PHP百钱买百鸡算法(穷举算法)

来源:互联网 发布:广告联盟挂机软件 编辑:程序博客网 时间:2024/06/07 07:21

小鸡5毛钱一只,母鸡3块钱一只,公鸡5块钱一只,问300块钱买100只鸡,有几种买法?

$xPrice   = 0.5;$yPrice   = 3;$zPrice   = 5;$price = 300;$count = 100;$zCount  = $price / $zPrice;$yCount  = $price / $yPrice;$zCount  = $price / $zPrice;$i = 1;for($x=0; $x<$zCount; $x++){    for($y=0; $y<$yCount; $y++)    {        for($z=0; $z<$zCount; $z++)        {            if((0.5 * $x + 3*$y + 5*$z == $price) && ($x + $y + $z == $count)){                echo $i,".小鸡:",$z,",母鸡:",$y,",公鸡:",$x,PHP_EOL;            }        }    }}

优化后

$xPrice   = 0.5;$yPrice   = 3;$zPrice   = 5;$price = 300;$count = 100;$zCount  = $price / $zPrice;$yCount  = $price / $yPrice;$zCount  = $price / $zPrice;$i = 1;for($x=1; $x<$zCount; $x++){    for($y=1; $y<$yCount; $y++)    {        $z = $count - $x - $y;            if((0.5 * $x + 3*$y + 5*$z == $price) && ($x + $y + $z == $count)){                echo $i,".小鸡:",$z,",母鸡:",$y,",公鸡:",$x,PHP_EOL;        }    }}
0 0
原创粉丝点击