Recursive and non-recursive solutions of Fibonacci sequence

Write a function, enter n, and find the nth term of the Fibonacci sequence (ie F(N)).

The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1

F(N) = F(N-1) + F(N-2), where N> 1. The Fibonacci sequence starts from 0 and 1, and the subsequent Fibonacci numbers are the addition of the previous two numbers And come out.

The answer needs to be modulo 1e9+7 (1000000007). If the initial result of the calculation is: 1000000008, please return 1.

Method 1: (Recursively, because it will repeatedly calculate a previously calculated value, unnecessary overhead will be generated, so here is a map defined to store the calculated value. But the method will still time out!)

        public int fib(int n) {
   Map<Integer,Integer> m=new HashMap<>();
   if (n < 2)
         return n;

       if(!m.containsKey(n)){
          m.put(n,(fib(n-1)+fib(n-2))%1000000007);
      }
       return m.get(n);
}

Method two: non-recursive

public int fib(int n) {
int constant=1000000007;
int fist=0;
int second=1;
int temp=0;
while(n-->0){
temp=(fist+second)%constant;
fist=second%constant;
second=temp%constant;
}
return fist;
}

 

 

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/115190814