Problem:
A newborn calf, a calf born four years later, will be born each year. There is a newborn calf. How many cows are there in 20 years?
Ideas:
This seed has the issue of "son", "son", "son" and "son". "There is a nested loop in the loop. At first glance, we can see that it is the first problem.
As a result, the first version appears: Public Long Compute1 ( Uint Years)
{
// Initialized to 1 ox
Long Count = 1 ;
If (Years <= 3 )
{
ReturnCount;
}
Int I = 4 ;
While (I <= Years)
{
Int Subyears = I - 3 ;
Count + = Compute1 (( Uint ) (Subyears ));
I ++ ;
}
Return ( Long ) Count;
}
However, this kind of loop method will make the CPU too tired. If you don't believe it, enter a 100 test to test the above method. After waiting for a long time, there will be no results. Please improve it, the old ox (the lord of the ox) and the calf (the Red Baby and grandma are planted together) have the same fertility ability, and their fertility curves are the same, so the calf can reuse the old ox's fertility experience, this solves the problem of repeated computing of the number of coincidences of a cow in the nth year. When the age is relatively large, the number of CPU operations is significantly reduced, the following is based on this idea Algorithm Hashtable table = New Hashtable ();
Public Long Compute ( Uint Years)
{
// Initialized to 1 ox
Long Count = 1 ;
If (Years <= 3 )
{
ReturnCount;
}
Int I = 4 ;
While (I <= Years)
{
Int Subyears = I - 3 ;
If (Table. containskey (subyears ))
{
Count=(Long) Table [subyears];
}
Else
{
Count+ =Compute ((Uint) (Subyears ));
}
If ( ! Table. containskey (subyears ))
{
Table. Add (subyears, count );
}
I ++ ;
}
Return ( Long ) Count;
}
TestProgramTest the above inference. The result is as follows:
1) when the input years is small, the first method takes a short time, but the time of the two methods is basically an order of magnitude.
2) When the input years is relatively large, for example, 40 or more, the second algorithm has a performance ratio of more than 100 compared with the first one, and the higher the input years, the poorer the performance ratio.
Test results:
20 years
50 years
Source program and test program:/files/jillzhang/howmoneycows.rar
-------------------------------------------------------
People are old, their heads are not easy to use, and occasionally use algorithms to train their brains, which can prevent premature aging. Haha
Jillzhang jillzhang@126.com