很传统的百鸡百钱问题,以前碰到这个问题直接解决就可以,没想过优化,碰到作者后才发现代码还是永无止境啊。
http://www.cnblogs.com/huangxincheng/archive/2012/08/05/2624156.html
作者网址,作者网址有详细的解说有兴趣的可以去看看,有关算法。
java代码如下
/** * @Author Peter_S * @Date 2018/5/30 */ public class Ces { /** * 百钱买百鸡的问题算是一套非常经典的不定方程的问题, * 题目很简单:公鸡5文钱一只,母鸡3文钱一只,小鸡3只一文钱, * 用100文钱买一百只鸡,其中公鸡,母鸡,小鸡都必须要有, * 问公鸡,母鸡,小鸡要买多少只刚好凑足100文钱。 * */ public static void main(String[] args) { long start1 =System.currentTimeMillis(); int i = 0; for (int x = 1;x<20;x++){ for (int y=1;y<33;y++){ i++; int z = 100 - x -y; if ((z%3 == 0) && (5*x + 3*y + z/3 == 100)){ System.out.println("公鸡" + x + "只;母鸡" + y + "只;小鸡 " + z + "只;" ); } } } System.out.println(i); System.out.println("耗时"+ (System.currentTimeMillis()-start1)); long start2 = System.currentTimeMillis(); int j = 0; int x,y,z; for (int k =1;k<=3;k++){ j++; x = 4*k; y = 25-7*k; z = 75 + 3*k; if ((z%3 == 0) && (5*x + 3*y + z/3 == 100)){ System.out.println("公鸡" + x + "只;母鸡" + y + "只;小鸡 " + z + "只;" ); } } System.out.println(j); System.out.println("耗时" + (System.currentTimeMillis()-start2)); } }
结果如下