问题如下:
购物帐单显示:
商品A的单价是7.98元,商品B的单价是18.70元,商品C的单价是35.50元;
总共花费 1000元。
问:三种商品各买了几件?
通过枚举可以找到并确定,有正整数唯一解:
A=45,B=2,C=17
请教,不采用枚举,获得正整数解的算法。
感谢回答!不过,这是一道小学奥数,所以不可能用枚举的方法。
这是fortran的枚举代码:
我猜想,有可能用类似“素数筛法”的算法,也就是通过一次枚举可以筛去(跳过)后续一大批枚举的算法。但是,没有能想出来具体办法。于是,才来请教各位大神的。
考虑笔算的条件,筛法枚举的步数应该少于10次。否则,难以手工计算的。
不管怎么样,这只能用枚举,条件不够,数学都没法计算,只能说减少枚举的次数。用Java写了个示例。测试正序用了20000多次,逆序用了不到2000次。
public static void main(String[] args) {
double aPrice = 7.98;
double bPrice = 18.70;
double cPrice = 35.50;
int cNum = (int) (1000 / cPrice);
for (int c = cNum; c > 0; c--) {
double cTotalPrice = c * cPrice;
int bNum = (int) ((1000 - cTotalPrice) / bPrice);
for (int b = bNum; b > 0; b--) {
double bTotalPrice = b * bPrice;
int aNum = (int) ((1000 - cTotalPrice - bTotalPrice) / aPrice);
for (int a = aNum; a > 0; a--) {
double aTotalPrice = a * aPrice;
int total = (int) (aTotalPrice + bTotalPrice + cTotalPrice);
if (total == 1000) {
System.out.println(String.format("a=%d,b=%d,c=%d", a, b, c));
return;
}
}
}
}
System.out.println("无结果");
}