张丘建《算经》中提出“百鸡问题”:鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。百钱买百鸡,问鸡翁、母、雏各几何?
分析:公鸡-cocks ,母鸡-hens,小鸡-chicks
cocks+hens+chicks=100
5*cocks+3*hens+chicks/3=100
★ 关键: 受百钱买百鸡的约束有 0≤cocks≤19, 0≤hens≤33, 0≤chicks≤100
★ 思路: 累试法(枚举法) 依次取cocks值域中的值,然后求其余两数,看是否满足题意
算法描述:
cocks=0
当cocks≤19时
{
找满足题意的hens,chicks数
cocks加1
}
细化:
cocks=0
当cocks≤19时
{
hens=0
当hens≤33时
{
找满足题意的chicks数
hens加1
}
cocks加1
}
再细化:
cocks=0
当cocks≤19时
{
hens=0
当hens≤33时
{
chicks=100-cocks-hens
如果 (5*cocks+3*hens+chicks/3=100) 则输出
hens加1
}
cocks加1
}
编写代码如下:
#include "stdio.h"
void main()
{
int cocks, hens, chicks;
printf ("cocks hens chicks\n");
printf ("-------------------\n");
cocks=0;
while (cocks <= 19)
{
hens=0;
while (hens <= 33)
{
chicks = 100 - cocks - hens;
if ( cocks * 5 + hens * 3 + chicks / 3 == 100 )
printf ("%5d %5d %5d\n", cocks, hens, chicks);
hens++;
}
cocks++;
}
printf ("-------------------\n");
}
运行结果:
===========================
cocks hens chicks
-------------------
0 25 75
3 20 77
4 18 78
7 13 80
8 11 81
11 6 83
12 4 84
-------------------
===========================
######################################更正########################################
经热心人评论指点, 做如下改正:
小鸡数必须为3的倍数:
算法描述:
cocks=0
当cocks≤19时
{
hens=0
当hens≤33时
{
chicks=100-cocks-hens
如果 (5*cocks+3*hens+chicks/3=100 且 小鸡数为3的倍数) 则输出
hens加1
}
cocks加1
}
代码:
#include "stdio.h"
void main()
{
int cocks, hens, chicks;
printf ("cocks hens chicks\n");
printf ("-------------------\n");
cocks=0;
while (cocks <= 19)
{
hens=0;
while (hens <= 33)
{
chicks = 100 - cocks - hens;
if ( cocks * 5 + hens * 3 + chicks / 3 == 100 && chicks % 3 == 0)
printf ("%5d %5d %5d\n", cocks, hens, chicks);
hens++;
}
cocks++;
}
printf ("-------------------\n");
}
运行结果:
===========================
cocks hens chicks
-------------------
0 25 75
4 18 78
8 11 81
12 4 84
-------------------
===========================
评论