#include <vector> std::vector<long int> as; long int a(size_t n){ if(n==1) return 1; if(n==2) return -2; if(as.size()<n+1) as.resize(n+1); if(as[n]<=0) { as[n]=-4*a(n-1)-4*a(n-2); } return mod(as[n], 65535); }
The above code example using memoization to compute a recursive formula based on some input n . I know this uses memoization because I wrote a purely recursive function that uses the same formula, but this one is much, much faster for much larger n values. I had never used vectors before, but I did some research and I understand their concept. I understand that memoization must store each calculated value, so that instead of repeating the same calculations, it can simply get the ones that have already been calculated.
My question is: how is this memory, and how does it work? I do not see the code in the code in which it checks if a value exists for n. Also, I don't understand the purpose of if(as[n]<=0) . This formula can give positive and negative values, so I'm not sure what this check is looking for.
Thank you, I think I'm close to understanding how this works, in fact it is a little easier than I thought.
I don't think the values ββin the sequence can be 0, so this should work for me, since I think n should start with 1.
However, if zero were a viable number in my sequence, in what other way could I solve it? For example, what if five never appear? Do I just need to fill my vector with five?
Edit: Wow, I get many other answers by checking the code and typing it. Thanks for helping everyone, I think I understand now.
source share