Basic algorithm question-hundred dollar buy hundred chicken
Title: Rooster 5 Text Money One, hen 3 text money A, chicken 3 only a penny, with 100 text money to buy 100 chickens, the rooster, hen, chicken all must have, ask rooster, hen, chicken to buy how many only just to fill 100 of money.
Let's start by analyzing:
Set the rooster for x only, hen for y only, chick for z only, available
x+y+z=100
5x+3y+z/3=100
since each chicken has a minimum of 1, the Rooster can have (100-3-1)/5, the hen can have up to (100-5-1)/3 only
We can then encode the implementation
//Buy the maximum number of cocksintGongji = ( --3-1) /5;//The maximum number of hens to buyintMuJi = ( --5-1) /3;//Because each type of chicken is at least one so I start from 1//Number of cocks for(inti =1; I <= Gongji; i++) {//Number of hens for(intj =1; J <= MuJi; J + +) {//Number of chicks intXiaoji = --I-j;//Rooster Money + hen's Money + chick's money intMoney =5* i +3* j + Xiaoji/3;//Because 3 chickens 1 cents so the number of chickens to take the remainder of 3 equals 0, and the total cost is equal to if(Xiaoji%3==0&& Money = = -) {System. out. println ("Rooster:"+ i +"Only, hen:"+ j +"Only, Chick:"+ Xiaoji +"Only"); } }}
Result of Operation
While the above code solves our problem, it is too complex in the actual application so we can optimize it again.
From the output above can be learned that the number of cocks is a multiple of 4, the number of hens is 7 decline, the number of chickens must be a multiple of 3.
Set the rooster for x only, the hen for y only, the chick for z only, can get:
X+y+z=100①
5x+3y+z/3=100②
solution ① can get Z=100-x-y;③
bringing ③ into the ② can be:
5x+3y+ (100-x-y)/3=100;
15x+9y+100-x-y=300;
14x+8y=200;
7x+4y=100;
4y=100-7x;
After analysis, the code can be improved to
How much does it cost to buy a total of chickens ?int sum= -;//Buy the maximum number of cocksintGongji = (sum-3-1) /5;//Because each type of chicken is at least one so I start from 1//Number of cocks for(inti =4; I <= Gongji; i + =4) {The number of known cocks, according to the equation 4y=100-7x; the number of hens available intMuJi = (sum-7* i)/4;number of chickens that are known to have cocks and hens intXiaoji =sum-I-muji;//Calculate Total Price intMoney =5* i +3* MuJi + Xiaoji/3;the number of chickens is 3 equals 0 and the total price equals 100, then test instructions if(Xiaoji%3==0&& Money = =sum&& muJi >0) {System.out.println ("Rooster:"+ i +"Only, hen:"+ MuJi +"Only, Chick:"+ Xiaoji +"Only"); }}
At this point, we have changed the complexity of the code from O (N2) to O (N1)
Basic algorithm problem-----hundred dollars to buy hundred chickens