What is a non recursive solution for Fibonacci-like sequence in Java?

前端 未结 10 1563
Happy的楠姐
Happy的楠姐 2020-12-01 18:23

Given this pseudo code of a function

f(0) = 1; 
f(1) = 3; 
f(n) = 3 * f(n - 1) - f(n - 2); // for n >= 2.

Is there a non recursive way o

10条回答
  •  醉酒成梦
    2020-12-01 18:53

    Answers here are correct, but they work in O(n), while you can do it in O(log n), exponentially faster. Observe that

    [f(n)  ] = [3 -1] [f(n-1)]
    [f(n-1)]   [1  0] [f(n-2)]
    

    Let vn be the vector [f(n), f(n-1)] and A the matrix as above, so you get vn = A vn-1, therefore vn = An-1 v1. Compute (n-1)-th power of matrix A using binary exponentiation and multiply it by v1. For more on linear recurrences see here.

提交回复
热议问题