Hundred money to buy hundred chicken problem is a very classical problem of indefinite equation, the topic is simple: Rooster 5 Money A, hen 3 money A, chicken 3 only a penny,
Buy 100 chickens with 100 cents, among them cocks, hens, chickens all must have, ask the rooster, hen, chicken to buy how many only just to make up 100 text money.
Analysis: It is estimated that pupils can now manually calculate the problem, but we use the computer to calculate, we can set the rooster for X, the hen for Y, the chicken for z, then we can draw the following indefinite equation
X+Y+Z=100,
5X+3Y+Z/3=100,
The following look at the range of x, Y, Z, because only 100 money, then 5x<100 = 0<x<20, the same 0<y<33, so z=100-x-y, good, we have analyzed clearly, the following can be encoded.
1 Public Static voidMain (string[] args) {2 //Cocks on the line3 for(intx = 1; x < 20; X + +) {4 //Hen's on the line5 for(inty = 1; Y < 33; y++) {6 //remaining Chicks7 intz = 100-x-y;8 if((z% 3 = = 0) && (x * 5 + y * 3 + Z/3 = = 100)) {9System.out.println ("Rooster" + x+ ", hen" +y+ ", chick" +z);Ten } One } A } -}
Operation Result:
Rooster 4, hen 18, Chick 78
Rooster 8, hen 11, Chick 81
Rooster 12, hen 4, Chick 84
The results come out, it is true that the problem is very simple, we need to know that the current time complexity is O (N2), the actual application of this complexity is not acceptable to you, up to the most acceptable is O (N).
So we have to optimize, from the results we can find such a rule: The rooster is a multiple of 4, the hen is 7 of the decline rate, the chicken is 3 of the rate of increase, where the law will definitely need us
Calculate this indefinite equation:
X+y+z=100①
5x+3y+z/3=100②
Make ②x3-① available.
7x+4y=100
=>y=25-(7/4) X③
And because the natural number of 0<y<100, it can make
X=4k④
④ into ③ can be
= Y=25-7k⑤
④⑤ into the ①
= Z=75+3k⑥
To guarantee the 0<x,y,z<100, the value of K can only be in the range of two-way, below we continue on the code:
1 int x, y, Z; 2 for (int k = 1; k <= 3; k++) {3 x = 4 * k; 4 y = 25-7 * k; 5 z = 3 * k; 6 System.out.println ("Rooster" + x+ ", hen" +y+ ", chick" +z "); 7 }
Operation Result:
Rooster 4, hen 18, Chick 78
Rooster 8, hen 11, Chick 81
Rooster 12, hen 4, Chick 84
This time we did the O (N) complexity, very good.
Algorithm-hundred money buy white chicken