f(0) = p
f(1) = q
f(2) = r
for n > 2
f(n) = af(n-1) + bf(n-2) + c*f(n-3) + g(n)
where g(n) = n* n* (n+1)
p,q,r,a,b,c are given The question is, How to find the nth term of this series.
Please help me in finding a better solution for this.
I have tried solving this using recursion. But that way is consuming high memory.
The problem is that for each call to
f
withn > 2
, it results in three extra calls tof
. For example if we callf(5)
, we get the following calls:We thus make one call
f(5)
, one call tof(4)
, two calls tof(3)
, four calls tof(2)
, three calls tof(1)
, and two calls tof(0)
.Since we make multiple calls to for example
f(3)
, it thus means that each time this will cost resources, especially sincef(3)
itself will make extra calls.We can let Python store the result of a function call, and return the result, for example with the
lru_cache
[Python-doc]. This technique is called memoization:This will result in a call graph like:
So now we will only calculate
f(3)
once, thelru_cache
will store it in the cache, and if we callf(3)
a second time, we will never evaluatef(3)
itself, the cache will return the pre-computed value.The above here can however be optimized, since we each time call
f(n-1)
,f(n-2)
andf(n-3)
, we only need to store the last three values, and each time calculate the next value based on the last three values, and shift the variables, like:A better way than recursion would be memoization. You just need to know the last three values for f(n). A solution in pseudocode could look like this:
This way you don't need to call the method recursively and keep all the values, that were calculated, on the stack, but just keep 4 variables in your memeory.
This should calculate much faster and use much less memory.