Question: "Chicken Weng A value Five, chicken mother a value three, chickens three valuable one".
Description: A rooster worth five money, a hen worth three money, three chickens worth a dollar, ask how to use 100 money to buy 100 chickens?
Set the rooster, hen, chickens respectively value x, Y and Z money.
A. Algorithm one: Poor lifting method
The
1<= x <=19,
1<= y <=32,
3<= z <=98 (step 3)
To solve the problem of poor lifting method:
Code
1 for(intx=1; x<= +; x + +)2 for(inty=1; y<= +; y++)3 for(intz=3; z<=98; z+=3)//Step size is 34 {5 if(x+y+z== -&&5*x+3*y+z/3== -)//Hundred-dollar hundred chicken condition6 {7printf" %d%d%d", x, Y, z);8 }9}
The brute-lifting method iterates through all the possible situations and finally gets the right results, which is the ability to play the computer's fast Computing
But it's all about throwing the problem to the computer and dealing with it is not what we're after, and in this matter, it can actually reduce the number of loops.
To the first floor, we know that "hundred money to buy hundred chickens" the problem of the two conditions need to be satisfied, the number one is the amount of 100, the other is 100 chickens,
In algorithm one we put this condition in the program to judge (if (x+y+z==&& 5*x+3*y+z/3==) ),
In the algorithm two I will first combine the equations of these two conditions into a set of equations, and then simplify the equations, and finally through the program to solve the problem.
B. Algorithm two: simplification of equations
Equations:
X+Y+Z=100,
5x+3y+z/3=100
The top-up is organized:
Y=25-7X/4,
Z=75+3x/4
x, y, and z need to be up-to-the-top, and by means of an integer 4.
Code:
for (int x= 4 ; X<=19 ; x+= 4 ) {y =25 - 7 *x/ =75 +3 *x/ 4 if (Y>0 && z<=< Span style= "color: #800080;" >98 ) printf ( " %d%d%d " ,x,y,z);}
The algorithm two cycles only 4 times to obtain the result, improves the efficiency.
So using the program to solve a mathematical problem, the first thing is to do a full analysis of the problem,
The problem can be turned into another form, so that the program is more concise and easy to implement, why not?
hundred dollars to buy hundred chickens