I'm not sure how you came up with this line:
return (2 * mysequence(n+1) + mysequence(n+2))/3;
But that's not correct. For one thing, mysequence(n)
would call mysequence(n+1)
(and mysequence(n+2)
), which would call mysequence(n+2)
, which would call mysequence(n+3)
, which would call mysequence(n+4)
, etc. - it should be easy to see that you'll never reach mysequence(0)
or mysequence(1)
(assuming n > 1
), thus it would keep going forever, or at least until you run out of memory, since you're increasing instead of decreasing the parameter in subsequent calls.
Let's start from the beginning by first converting this:
a(n+2) = -2a(n+1) + 3a(n)
Into something that looks more like the code: (by subtracting 2 from each n+c
)
(on the left side we'd like a(n)
, since the function takes the parameter n
, not n+2
)
a(n) = -2a(n-1) + 3a(n-2)
Now we simply need to put that in the code. Replace:
return (2 * mysequence(n+1) + mysequence(n+2))/3;
With
return -2 * mysequence(n-1) + 3 * mysequence(n-2);
Also, you don't really need to specifically cater for n == 2
- it will be handled correctly by the above statement.