package main //公鸡5钱1只,母鸡3钱一只,小鸡1钱三只 需要用百钱买百鸡 //100钱的话 公鸡20或者母鸡33 小鸡100 func main() { count := 0 for i := 0; i <= 20; i++{ for j := 0; j <= 33; j++ { for k := 0; k <= 100; k++ { if i+j+k == 100 && i*5+j*3+k/3 == 100 && k%3 == 0 { println(i, j, k) } count++ } } } println(count) count = 0 //优化1 for i := 0; i <= 20; i++{ for j := 0; j <= 33; j++ { for k := 0; k <= 100; k+=3 { if i+j+k == 100 && i*5+j*3+k/3 == 100 { println(i, j, k) } count++ } } } println(count) count = 0 println() //优化2 总共一百只鸡 100-公鸡-母鸡等于小鸡 只需要判断百钱 for i := 0; i <= 20; i++{ for j := 0; j <= 33; j++ { k := 100 - i - j if k % 3 == 0 && i*5+j*3+k/3 == 100{ println(i, j, k) } count++ } } println(count) //优化3 k每次加三个 就避免了判断k%3==0, j<0 表明公鸡小鸡买的太多了,直接进入下一次迭代减少执行次数 count = 0 for i := 0; i <= 20; i++{ for k := 0; k <= 100; k += 3 { j := 100 - i - k if j < 0 { continue } if i*5+j*3+k/3 == 100{ println(i, j, k) } count++ } } println(count) }
优化三跑得快 输出如下
0 25 75
4 18 78
8 11 81
12 4 84
72114
0 25 75
4 18 78
8 11 81
12 4 84
24276
0 25 75
4 18 78
8 11 81
12 4 84
714
0 25 75
4 18 78
8 11 81
12 4 84
644