Fibonacci series log (n) Algorithm

Source: Internet
Author: User

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;

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.