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
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.