The idea stems from the question: a person can take one or two steps at a time, and how many steps can be taken up to 20 levels?
This is a Fibonacci series: there is a method of boarding the first level; there are two methods of boarding the second level; three methods of boarding the third level; four levels of boarding, there are five methods ...... So, 1, 2, 3, 5, 8, 13 ......
We will also find that:
F (3) = F (2) + F (1 );
F (4) = 2 * (F2) + 1 * F (1 );
F (5) = 3 * (F2) + 2 * F (1 );
F (6) = 5 * F (2) + 3 * F (1 );
..........
F (n) = A * f (x) + B * f (y );
A and B are also the numbers in the Fibonacci series:
When a + x = N & B + y = n-1 & X = Y + 1, the equation is true;
The following O (log (N) algorithm is obtained:
/// <Summary>
/// Basic principle:
/// If n is an even number, f (n) = f (n/2) * f (n/2) + f (n-1) * f (n-1 );
/// When n is the base, f (n) = f (n/2 + 1) * f (n/2) + f (n/2) * f (n/2-1 );
/// </Summary>
/// <Param name = "n"> </param>
/// <Returns> </returns>
Public static long Fn2 (int n)
{
If (1 <n)
{
VaR steps = new stack <int> ();
While (n> 2)
{
Steps. Push (N );
N/= 2;
}
Long R1 = 2, R2 = 3;
While (steps. Count> 0)
{
Int tmp = steps. Pop ();
If (3 <tmp)
{
Long tr1;
Long tr2;
If (0 = tmp % 2)
{
Tr1 = 2 * r1 * r1 + r2 * r2-2 * r1 * r2;
Tr2 = 2 * r1 * r2-r1 * r1;
R1 = tr1;
R2 = tr2;
}
Else
{
Tr1 = 2 * r1 * r2-r1 * r1;
Tr2 = r1 * r1 + r2 * r2;
R1 = tr1;
R2 = tr2;
}
}
Else
{
R1 = 3;
R2 = 5;
}
}
Return r1;
}
If (1 = n) return 1;
Return-1;
}