Encountered an interesting problem, and calculated the efficiency of the two methods, and found that if all the combinations are exhausted, there are as many as 1,000,000 permutations ~ so it is simplified to 600 times. So, one of your conditions, or an operation, may be thousands of times more efficient!
<?php
header("Content-Type:text/html;charset=utf-8");
//百钱买小鸡
/* 公鸡5文钱1只,母鸡三文钱一只,小鸡一文钱三只。 现在用100文钱共买了100只鸡, 问这100只鸡中,公鸡,母鸡,小鸡各是多少只? */ $start = microtime(true); //写法一 穷举所有排列:计算1000000次。 for($g = 1; $g <= 100; $g++){ for($m = 1; $m <= 100; $m++){ for($x = 1; $x <= 100; $x++){ if($g+$m+$x == 100 && $g*5+$m*3+$x/3==100){ echo "公,母,雏,分别为:".$g." ".$m." ".$x."<br />"; } //计算排列组合次数 if($g == 100 && $m == 100 && $x == 100){ echo "排列次数为:".$g*$m*$x; } } } } echo "<br />"; $end = microtime(true); echo "函数执行时间为:".($end - $start);//计算函数运行时间。 echo "<br />"; //写法二:简化组合. $start = microtime(true); for($g = 1; $g < 20; $g++){ for($m = 1; $m <= 33; $m++){ $x = 100 - $g - $m; if($g+$m+$x == 100 && $g*5+$m*3+$x/3==100){ echo "公,母,雏,分别为:".$g." ".$m." ".$x."<br />"; } //计算排列组合次数 if($g == 19 && $m == 33){ echo "排列次数为:".$g*$m; } } } echo "<br />"; $end = microtime(true); echo "函数执行时间为:".($end - $start);//计算函数运行时间。 echo "<br />"; ?>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
Output result 1:
male, female, chick, respectively: 4 18 78
male, female, chick, respectively: 8 11 81
male, female, chick, respectively: 12 4 84
The number of permutations is: 1000000 The
execution time of the function is: 0.10584402084351
Let's take a look at the second set of algorithms ~ a thousand times worse ~ although it is milliseconds.
Output result 2:
male, female, chick, respectively: 4 18 78
male, female, chick, respectively: 8 11 81
male, female, chick, respectively: 12 4 84
The number of permutations is: 627 The
execution time of the function is: 0.00016307830810547