Question:
How many cows are there in the nth year?
Specific analysis:
1. Analysis questions: (A cow is generated every year starting from the fourth year of birth)
Time (year) Number of immature cows (head) Total number of mature cows (head)
1 1 0 1
2 1 0 1
3 1 0 1
4 0 1 1
5 1 1 2
6 2 1 3
7 3 1 4
8 3 2 5
9 4 3 7
10 6 4 10
We can see that a1 = 1, a2 = 2, A3 = 3, A4 = 4, A5 = A4 + A1 and so on, according to this rule, an = An-1 + an-4. this rule is very important, because we can obtain a similar rule from it (for example, from the birth of the first year of M, a cow is born every year, the law obtained is fn = Fn-1 + FN-M (n> m )).
RecursionAlgorithm:
// Recursion
Public Static Int Getcowrecursive ( Int Year)
{
Int Result = 0 ;
If (Year > 4 )
Result = Getcowrecursive (Year - 1 ) + Getcowrecursive (Year - 4 );
Else
Result = 1 ;
Return Result;
}
// Non-recursion
Public Static Int Getcow ( Int Year)
{
Int F1 = 1 ;
Int F2 = 1 ;
Int F3 = 1 ;
Int F4 = 1 ;
Int FIB = 0 ;
If (Year > 4 )
{
For ( Int I = 5 ; I <= Year; I ++ )
{
FIB = F4 + F1;
F1 = F2;
F2 = F3;
F3 = F4;
F4 = FIB;
}
Return FIB;
}
Else
{
Return 1;
}
}