Fibonacci non-recursive algorithm)

Source: Internet
Author: User
Tags mathematical functions

The Fibonacci series was introduced by the mathematician Leonardo Fibonacci using rabbit breeding as an example. It is also known as the "Rabbit series ".
Fibonacci sequence definition:
When n = 1, FIB (n) = 1
N> 2, FIB (n) = fib (n-2) + fib (n-1)

public class FibTest {   
public static void main(String[] arags){
long begin = System.currentTimeMillis();
System.out.println(fib(10));
long end = System.currentTimeMillis();
System.out.println(end - begin);
}
public static long fib(int n){
if(n < 3)
return 1;
else{
long a = 1;
long b = 1;
for(int i = 2 ; i < n-1 ;i++){
b = a + b;
a = b - a;
System.out.println("a = "+a +" b = "+b);
}
return a + b;
}
}
}

The biggest advantage of this algorithm is that there is no repeated computing, so the efficiency is much faster than the recursive algorithm.

The following briefly compares the differences between Recursion and non-recursion:

The number of rabbits in the n (n> 3) month is obtained by using a non-recursive algorithm. The number of rabbits in the previous two months is calculated and recorded starting from the first 3rd months.

The number of rabbits in the previous month until the N months, the n-1 months and The N-2 months are used together to find the result.

Result: The time complexity is O (n );

What is the result of recursive algorithms? Solve fib (N), push it to solve fib (n-1) and FIB (n-2 ). That is to say, to calculate fib (N), you must calculate

FIB (n-1) and FIB (n-2), while the calculation of Fib (n-1) and FIB (n-2), must first calculate fib (n-3) and FIB (n-4 ). And so on until the calculation of Fib (1) and FIB (0 ),

Results 1 and 0 can be obtained immediately. In the recurrence stage, termination of recursion is required. For example, in function fib, when n is 1 and 0. In the regression phase, when

After obtaining the solution of the simplest case, return the result step by step to obtain the solution of a slightly complex problem. For example, after obtaining fib (1) and FIB (0), return the result of Fib (2) ,......,

After obtaining the results of Fib (n-1) and FIB (n-2), the results of Fib (n) are returned. The time complexity is O (2n) (2 in brackets ).

Http://blog.csdn.net/qiao000_000/archive/2009/11/24/4856431.aspx

Bytes -----------------------------------------------------------------------------------------------------------------

Fibonacci series:1,1,2,3,5,8,13, 55 ,......,

Recursion is used to calculate the value of a certain number of digits in a series, And a series formula is used for calculation. It is mainly used to familiarize yourself with the use of mathematical functions.

The recursion efficiency is always poor. It takes a long time to calculate the value of 40th items.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Namespace c4_t4
{
Class Program
{
Static void main (string [] ARGs)
{
Console. Write ("Enter the number of Fibonacci series to be obtained :");
Int n = convert. toint32 (console. Readline ());
// Recursive Implementation

Console. writeline ("the {0} items recursively calculated by the Fibonacci series are: {1}", N, calculate (n ));

// Use the formula

// {[(1 + √ 5)/2] ^ N-[(1-√ 5)/2] ^ n}/√ 5

Double K5 = math. SQRT (5 );
Double sum2 = math. floor (math. pow (1 + K5)/2), n)-math. pow (1-K5)/2), N)/K5 );
Console. writeline ("the {0} item calculated by the Fibonacci series formula is: {1}", N, sum2 );
Console. Readline ();
}

        static int Calculate(int n)
        {
            if (n <= 1)
            {
                return n;
            }
            else
            {
                return Calculate(n - 1) + Calculate(n - 2);
            }
        }
    }
}

Bytes -------------------------------------------------------------------------------------------------------------------------------

Today I did nothing, so I revisited the recursive algorithm. We suddenly found that recursive algorithms are very useful.

The first question I encountered was: Calculate the Array {, 5, 8 .......} the 30th-bit value does not require recursion. I wrote the following code:

 

Static void main (string [] ARGs)
{

Int [] num = new int [30];
Num [0] = 1;
Num [1] = 1;
Int first = num [0];
Int second = num [1];
For (INT I = 2; I <num. length; I ++)
{
Num [I] = first + second;
First = second;
Second = num [I];
}
Console. writeline (Num [29]);
Console. Readline ();

}

It is very cumbersome to write, so it is easy to understand and understand. The following code is used:

Static void main (string [] ARGs)
{

Console. writeline (process1 (30 ));
Console. Readline ();
}
Public static int process1 (int I)
{

// Calculate the {30th, 5, 8 ......} bits of the array.
If (I = 0) return 0;
If (I = 1) return 1;
Else
Return process1 (I-1) + process1 (I-2 );
}
I have done some exercises:

1. Calculate the value of 1 + 2 + 3 + 4 +... + 100

Static void main (string [] ARGs)
...{
Console. writeline (process2 (100 ));
Console. Readline ();
}
Public static int process2 (int I)
...{
// Calculates the value of 1 + 2 + 3 + 4 +... + 100
If (I = 0) return 0;
Return process2 (I-1) + I;

}
2. Calculate the value of 1-2 + 3 +-4 + 5-6 + 7-8 + 9

Static void main (string [] ARGs)
...{

Console. writeline (process3 (9)-process3 (8 ));
Console. Readline ();
}

Public static int process3 (int I)
...{
// Calculate the value of 1-2 + 3 +-4 + 5-6 + 7-8 + 9
If (I = 0) return 1;
If (I = 1) return 2;
Else return process3 (I-2) + I;
}
3. Tower of Hanoi Problems

Static void main (string [] ARGs)
...{
Hanoi (5, 'A', 'B', 'C ');
Console. Readline ();
}
Public static void Hanoi (int n, char a, char B, char C)
...{
// Tower of Hanoi Problems
// Move n plates from seat a with seat B to seat C
If (n = 1) Move (a, c );
Else
...{
Hanoi (n-1, A, C, B );
Move (a, c );
Hanoi (n-1, B, A, C );
}

}
Public static void move (char startplace, char endplace)
...{
Console. writeline ("move {0} to {1}", startplace, endplace );
}
4. Use recursion to convert an integer N into a string. For example, if you input 483, the number of digits of the output string "483". N is uncertain. It can be an integer of any digits.

Static void main (string [] ARGs)
...{
Inttostring (483 ,"");
Console. Readline ();
}
Public static void inttostring (INT input, string output)
...{
// Use recursion to convert an integer N into a string. For example, if you input 483, the number of digits of the output string "483". N is uncertain. It can be an integer of any digits.
// String output = "";
Output = input % 10 + output;
If (input/10! = 0)
...{
Inttostring (input/10, output );
}
Else console. writeline (output );

Http://blog.csdn.net/inkstone2006/archive/2008/01/22/2057853.aspx

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.