初级系列1.百钱百鸡问题
百钱百鸡问题
问题描述
一只公鸡值五钱,一只母鸡值三钱,三只小鸡值一钱,现在要用百钱买百鸡,请问公鸡,母鸡,小鸡各多少只?
问题分析
|--公鸡的数量应该在0 - 20之间
|--同理母鸡的数量应该在0 - 33之间
|--将公鸡,母鸡,小鸡的数量分别设为
cock,hen,chicken
则cock + hen + chicken = 100 将问题转化为解不定方程组的问题
不定方程组:
cock + hen + chicken = 100
5cock + 3hen + chicken/3 = 100
算法设计
穷举法,三重循环 时间复杂度 (n^3)
#include <stdio.h>
int main(void)
{
int cock, hen, chicken;
for (cock = 0; cock <= 20; cock++) { /* !<外层循环控制公鸡数量取值范围0~20 */
for (hen = 0; hen <= 33; hen++) { /* !<内层循环控制母鸡数量取值范围0~33 */
for (chicken = 0; chicken <= 100; chicken++) {
/* !<内层循环控制小鸡数量取值访问0-100 */
if ((5*cock + 3*hen + chicken/3.0 == 100) &&
(cock + hen + chicken == 100)) {
printf("cock = %2d, hen = %2d, chicken = %2d\n", cock, hen, chicken);
}
}
}
}
}
/* !< output */
cock, hen, chicken = 0 25 75
cock, hen, chicken = 4 18 78
cock, hen, chicken = 8 11 81
cock, hen, chicken = 12 4 84
#!/bin/python3
cocks = 20
hens = 33
chickens = 100
for cock in range(cocks):
for hen in range(hens):
for chicken in range(chickens):
if cock + hen + chicken == 100 and cock * 5 + hen *3 + chicken / 3.0 == 100:
print("cock, hen, chicken =", cock, hen, chicken)
/* !< output */
cock, hen, chicken = 0 25 75
cock, hen, chicken = 4 18 78
cock, hen, chicken = 8 11 81
cock, hen, chicken = 12 4 84