Recursive and non-recursive algorithms of the Fibonacci sequence

Source: Internet
Author: User

The Recursive Algorithms of the Fibonacci sequence are familiar to everyone:

// The value of item n in the Fibonacci sequence
// Recursive Algorithm
Unsigned int fib1 (unsigned int N)
{
If (n = 1 | n = 2)
Return 1;
Else
Return fib (n-1) + fib (n-2 );
}

The disadvantage of recursive algorithms is that the efficiency is too low. The following is a non-recursive algorithm:

// The value of item n in the Fibonacci sequence
// Non-recursive algorithm
Unsigned int fib2 (unsigned int N)
{
Unsigned int nret, NP, NPP; nret = NP = NPP = 1;
If (n = 1) | (n = 2 ))
Return nret;

For (unsigned int I = 3; I <= N; I ++)
{
Nret = NP + NPP;

NPP = NP;
NP = nret;
}

Return nret;
}

Fibonacci (Fibonacci) sequence:
FIB (n) = fib (n-1) + fib (n-2), n> 1, FIB (1) = fib (2) = 1
That is, the first and second items of the sequence are 1, starting from the third item, and the last one is the sum of the first two items.
The first eight items of the sequence are:
1, 1, 2, 3, 5, 8, 13, 21

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.