|
>Beautiful. I guess beauty is in the eye of the beholder. A simpler way to analyze this problem is noticing the f(n-3) term implies your function has to memorize up to 3 previous results. Then just use the coefficients from the formula to cycle the next result into memory. Using algebra and generating new coefficients as per the OP's solution is unnecessary. function f(n)
if n<3 then return n end
local a, b, c = 0, 1, 2
for i=3,n do
a, b, c = b, c, c+2*b+3*a
end
return c
end
|
In fact the exact same reasoning can be used to derive the closed form expression for the Fibonacci numbers [2], which are defined by a recurrence relation similar to the one in the OP. You raise the corresponding 2x2 matrix to the nth power by going to the eigenbasis where the matrix becomes diagonal, raising the values on the diagonal (which turn out to be the golden ratio (phi) and -1/phi) to the nth power, then changing the basis back.
[1] http://en.wikipedia.org/wiki/Exponentiation_by_squaring
[2] http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_ex...