Written interview questions: Frog Jumping and Fibonacci Sequence

     Originally published in:

 

 

      This weekend, it happens to be Programmer's Day, let’s talk about the Frog Jump and the Fibonacci Sequence. Many years ago, when I was interviewing the W department of T company, I encountered the problem of frog jumping.

 

      Questions are as follows:

      There are n steps, and the frog can only jump 1 or 2 steps at a time. Find the number of ways to jump to n steps.

      (1) When n> 1000, write a program to solve it.

      (2) Find the general term formula.

 

 

      I have to say that it is still difficult to solve this problem at the interview site. Let f(n) be the number of ways the frog jumps up to n steps, then:

f(1) = 1

f(2) = 2

f(n + 2) = f(n + 1) + f(n)

       

      This is a classic Fibonacci sequence, which can be solved directly by recursion:

func fib(n int) int {
    if n <= 0 {
        // 异常处理
    }

    if n == 1 || n == 2 {
        return n
    }

    return fib(n - 1) + fib(n - 2)
}

 

      However, when n>1000, f(n) is a very large value. Obviously, the above method cannot be used. To deal with large numbers, you can refer to the previous article: Written Interview Question: Factorial Question of 1000 .

 

 

      So, how to find the general term formula? There are many methods, such as characteristic root method, matrix method, generating function method, and Z transform method.

      Here is a method that high school students can understand, that is, the method of constructing a sequence of numbers:

 

       The application of Fibonacci sequence is very extensive. Problems such as frog jumping from platform, rabbit reproduction, and floor tiles are all typical Fibonacci sequence problems.

 

       Have a nice weekend and a happy programmers day. I wish you all get your favorite offer.

 

 

Guess you like

Origin blog.csdn.net/stpeace/article/details/110419390