问题如下:
共有100匹马和100袋粮食,其中大马驮三袋,小马驮两袋,两个小马崽驮一袋,请问大马小马小马崽恰好驮完,各多少匹?
实现代码1:
public static void getSum() { int bigHorse = 0; //大马 int smallHorse = 0; //小马 int minHorse = 0; //小马崽,小马崽必须是偶数 for (minHorse = 0; minHorse < 100; minHorse += 2) { bigHorse = (3 * minHorse - 200) / 2; smallHorse = 100 - bigHorse - minHorse; if (bigHorse < 0 || smallHorse < 0) { continue; } System.out.println("大马:" + bigHorse + " 小马:" + smallHorse + " 小马崽:" + minHorse); } }代码分析:
列出两个方程式,3x + 2y + z/2 = 100, x + y + z = 100,
由于小马崽必须是偶数,所以可从小马崽入手,将x和y分别转换为只与z有关的方程式,转换后x = (3z - 200)/2,用小马崽的个数作为循环,判断即可;
实现代码2:
public static void getSum2() { for (int bigHorse = 0; bigHorse <= 20; bigHorse++) { int temp = 100 - 5 * bigHorse; if (temp % 3 == 0) { int smallHorse = temp / 3; int minHorse = 100 - bigHorse - smallHorse; if (minHorse % 2 == 0) { System.out.println("大马:" + bigHorse + " 小马:" + smallHorse + " 小马崽:" + minHorse); } } } }代码分析:
将上面两个方程式,转换成只与x和y有关的方程式,即5x + 3y = 100,其中y = (100 - 5x)/3,因为x,y,z 全是非负数,所以x<=20,以x的个数作为循环判断即可;