Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does this C++ function use memoization?
    primarykey
    data
    text
    <pre><code>#include &lt;vector&gt; std::vector&lt;long int&gt; as; long int a(size_t n){ if(n==1) return 1; if(n==2) return -2; if(as.size()&lt;n+1) as.resize(n+1); if(as[n]&lt;=0) { as[n]=-4*a(n-1)-4*a(n-2); } return mod(as[n], 65535); } </code></pre> <p>The above code sample using memoization to calculate a recursive formula based on some input <code>n</code>. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of <code>n</code>. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated. </p> <p>My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the <code>if(as[n]&lt;=0)</code>. This formula can yield positive and negative values, so I'm not sure what this check is looking for.</p> <hr> <p>Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.</p> <p>I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1. </p> <p>However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?</p> <p>Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload