The original: The classic algorithm daily exercise--the first question hundred money to buy hundred chickens
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, hen for y, chicken for z, then we
The following indefinite equations can be obtained,
X+Y+Z=100,
5X+3Y+Z/3=100,
Let's take a look at the range of x, Y, z values.
Because only 100 money, then 5x<100 = 0<x<20, the same 0<y<33, so z=100-x-y,
Well, we've already analyzed it, and we can encode it below.
1 class Program2 {3 Static voidMain (string[] args)4 {5 //Cocks on the line6 for(intx =1; X < -; X + +)7 {8 //Hen's on the line9 for(inty =1; Y < -; y++)Ten { One //remaining Chicks A varz = --X-y; - - if((z%3==0) && (x *5+ y *3+ z/3== -)) the { -Console.WriteLine ("Rooster: {0} only, hen: {1} only, chick: {2} only", x, Y, z); - } - } + } - Console.read (); + } A}
The results come out, indeed this problem is very simple, we have to know that the current time complexity is O (N2), the actual application of this complexity is not acceptable to you, up to the maximum
People accept 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 increase in rate, the law where
Come, we must 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 only one, and below we continue on the code.
1 class Program2 {3 Static voidMain (string[] args)4 {5 intx, y, Z;6 7 for(intK =1; K <=3; k++)8 {9x =4*K;Teny = --7*K; Onez = the+3*K; A -Console.WriteLine ("Rooster: {0} only, hen: {1} only, chick: {2} only", x, Y, z); - } the - Console.read (); - } -}
This time we did the O (N) complexity, very good, at least to the extent that I can accept, perhaps we feel the charm of mathematics, yes, because ....
Mathematics is the Queen of Science. The emperor is the nature of physics ...
Classic algorithm Daily Walkthrough--the first question hundred money to buy hundred chickens