首页 > 代码库 > 40斤西瓜3人分,求分法

40斤西瓜3人分,求分法

该题最核心的思路是西瓜一共40斤,只要3个人分到的西瓜斤数总和等于40即可,所以,即有如下解决方法:

<?php
$aa = range(1,40);
$bb = array();
foreach($aa as $k=>$val){
  foreach($aa as $v){
    foreach($aa as $vl){
      $sum = $val+$v+$vl;
      if($sum == 40){
        $bb[$k][0] = $val;
        $bb[$k][1] = $v;
        $bb[$k][2] = $vl;
      }
    }
  }
}
echo ‘<pre>‘;
print_r($bb);
exit;
?>

输出结果为:

Array
(
  [0] => Array
    (
      [0] => 1
      [1] => 38
      [2] => 1
    )
  [1] => Array
    (
      [0] => 2
      [1] => 37
      [2] => 1
    )
  [2] => Array
    (
      [0] => 3
      [1] => 36
      [2] => 1
    )
  [3] => Array
    (
      [0] => 4
      [1] => 35
      [2] => 1
    )
  [4] => Array
    (
      [0] => 5
      [1] => 34
      [2] => 1
    ) 
   ...
   ...
   ...

 

摘自:http://www.jb51.net/article/116623.htm

40斤西瓜3人分,求分法