The sword refers to the Fibonacci sequence of offer--

Source: Internet
Author: User
Tags pow
1. Description of the problem

We all know the Fibonacci sequence, and now you're going to need to enter an integer n, so you output the nth item in the Fibonacci sequence.
n<=39 2. Solution Method

First, we have to make clear the Fibonacci sequence, because there is some controversy about the Fibonacci series, and the correct Fibonacci sequence is this: 0,1,1,2,3,5,8 ...

But when we touch the Fibonacci sequence, it's made by a rabbit, so it's mistaken for 1,1,2,3,5,8 ...

Furthermore, the first few items of our programmers are starting from the No. 0, and there is no objection. Then we begin to solve the problem. This is actually a very old, and we are very familiar with the topic, then how to solve it. 2.1 Level1

Recursion
As I said in the last lecture, the subject is so familiar that we are familiar with its formula:
F (n) =f (n−1) +f (n−2) f (n) =f (n-1) +f (n-2)
Therefore, for the sake of convenience, we naturally think of recursion:

public static int Fibonacci (int n) {
        if (n<=1) return
            N;
        else{return
            Fibonacci (n-1) +fibonacci (n-2);
        }
    

This way, I believe that the algorithm to do the problem must know, but this will have a large number of redundant calculations, once given a particularly large number, this can only be stackoverflow. So if we save the number of these numbers, we're done. This is Level2. 2.2 Level2

Iterations
As Level1 said, if we calculate all the numbers well, then there's no redundancy to compute. That's right:

    Array method, which reduces the duplication of computations. public
    static int Fibonacci (int n) {
        if (n<2) {return
            n;
        }
        else{
            int[] array=new int[n+1];
            array[0]=0;
            Array[1]=1;
            for (int i=2;i<=n;i++) {
                array[i]=array[i-1]+array[i-2];
            }
            return array[n];
        }
    

But this is really enough to optimize the. Would it be too much of a waste of space. Yes, here's what we do with the idea of dynamic planning, which is Level3. 2.3 Level3

Dynamic planning is about state transition, which means that for this Fibonacci sequence, just consider the current value and the previous 2 values. You can perform a state transition once per loop.

    Dynamic planning public
    static int Fibonacci (int n) {
        //first 2 number
        int last=0;
        First 1 number
        int recent=1;
        Current number
        int now=n;
        while (n>=2) {
            now=last+recent;
            last=recent;
            Recent=now;
            n--;
        }
        return to now;
    }

But this seems to be not enough simplicity, let's optimize:

    The idea of dynamic programming simplifies the public
    static int Fibonacci (int n) {
        int last=0;
        int recent=1;
        while (n-->0) {
            recent+=last;
            last=recent-last;
        }
        return to last;
    }

In this case, is very concise state, is basically a valid statement. Well, the time complexity is already at O (n) level. It's supposed to end here. 2.4 Level4

NO. NO. NO. Of course not optimal, because if you want to optimize, time complexity can be reduced to O (Logn). Let's see how it's solved.

* O (LOGN) Solution: by f (n) = f (n-1) + f (n-2), you can know
         * [f (n), F (n-1)] = [F (n-1), F (n-2)] * {[1,1],[1,0]}     
         * So the final simplification is: [F (N), F (n-1 ) = [1,1] * {[1,1],[1,0]}^ (n-2)     
         * So the core here is:     
         * 1. Matrix multiplication     
         * 2. Matrix fast Power (because without fast power algorithm, time complexity can only reach O (n))
    * * public static int Fibonacci4 (int n) {
            if (n < 1) 
            {return
                0;
            }
            if (n = = 1 | | n = = 2) 
            {return
                1;
            }
            Int[][] base = {{1,1},
                    {1,0}};
            N-2 Power
            int[][] res = Matrixpower (base, n-2) for base matrix;
            According to [F (n), F (n-1)] = [1,1] * {[1,1],[1,0]}^ (n-2), f (n) is
            //1*res[0][0] + 1*res[1][0] return        
            res[0][0] + res[1][ 0];
    }   

There are two additional ways to do this:

Matrix multiplication public static int[][] Multimatrix (int[][] m1,int[][] m2) {//Parameter judgment what is not given, if the matrix is n*m and m*p, then the result is n*p I
        nt[][] res = new Int[m1.length][m2[0].length]; for (int i = 0; i < m1.length. i++) {for (int j = 0; J < M2[0].length; j) {for ( int k = 0; K < M2.length;
                    k++) {Res[i][j] + = m1[i][k] * M2[k][j];
    }} return res; }/* Fast power of Matrix: * 1. If not the matrix, ask you to seek m^n, how to do O (Logn). The answer is the fast power of an integer: * If it does not overflow, such as 10^75, 75 used in binary notation: 1001011, then the corresponding is: * 10^75 = 10^64*10^8*10^2*10 * 2. Convert integers to moments Array, is the same * * public static int[][] Matrixpower (int[][] m, int p) {int[][] res = new Int[m.length][m[0
        ].length];
        First the res is set to the unit matrix for (int i = 0; i < res.length i++) {res[i][i] = 1;
        }//Unit matrix multiply arbitrary matrices for the original matrix//to hold each square int[][] tmp = m; p A for (; P!= 0 p) at one time for Each loop >>= 1) {//If the bit is Non-zero, it should be multiplied by if ((p&1)!= 0) {res = Multimatrix (res, TMP);
        ///Every time the result of the square is saved TMP = MULTIMATRIX (TMP, TMP);
    return res;    }

In this case, the time complexity can be reached O (Logn) level. Some students may say, write so much code, this time complexity will not increase. In the previous topic, we made a comparison between O (Logn) and O (n). If you know the difference, you can understand that so many of the above code will only increase the size of the coefficient, compared to the dozens of times times the difference, this increase in the coefficient will continue to be ignored as n increases. 2.5 Level5

Black Magic is here. O (LOGN) time complexity is already good enough, how, still can continue to optimize. That's right. You're not mistaken. That's right. You can also continue to optimize.

If you know how to combine math, then the black magic here can reduce the time complexity to O (1), right, you are not mistaken, is really O (1), and the length of the code will be greatly shortened. The name of the black magic is called: the recursive relation is solved by generating function.

Specific academic knowledge of the students interested in the words can be consulted, the following code:

The recursive relation is solved with the generating function, and the time complexity O (n) public
    static int Fibonacci (int n) {
        double root=math.sqrt (5);
        return (int) Math.Round (Math.pow ((1 + root)/2), N)/Root-math.pow (((1-root)/2), N)/root);
    

Yes, this is the 2 words, if you are happy, you can condense into 1 words. What do you mean by so long a string?
I'll rewrite it like this and everyone will understand:

public static int Fibonacci (int n) {
        double root=math.sqrt (5);
        Double X1=math.pow (((1 + root)/2), n)/root;
        Double X2=math.pow ((1-root)/2), n)/root;
        return (int) math.round (x1-x2);
    }

The reason for using Math.Round () is because double has so little error, so you need to use rounding to fill this residual. It is actually the solution of the recursive formula:
F (n) = (1+5√2) n− (1−5√2) n5√f (n) =\frac{(\frac {1+\sqrt{5}}{2}) ^n-(\frac {1-\sqrt{5}}{2}) ^n}{\sqrt{5}}

3. Algorithm Analysis 3.1

In the first scenario, the simplest, the time complexity is this, the first n and the formula is:
SUM (n) =f (n+2) −1 sum (n) =f (n+2)-1
which
F (n) = (1+5√2) n− (

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.