Дмитрий Рыбас on Fri, 12 Jul 2019 09:40:16 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Using local variable for memoizing in recursion


I'm trying to write a function that computes a number of partitions of integer n with no more that k parts.
As I don't know if there exist short way (and Ramanujan did not give us the formula for that), I use long way: recursion.

M=Map();
memo_p(n,k)={
my(res=0);
if(n==0 && k==0,return(1));
if(k<1,return(0));  
if(mapisdefined(M,[n,k],&res),return(res));
if(k>=n,res=numbpart(n);mapput(M,[n,k],res);return(res));
res=memo_p(n,k-1)+memo_p(n-k,k);
mapput(M,[n,k],res);
return(res);}

So, calling memo_p(n,k) returns desired number of partitions, it's O'k

But, all memoized values remain in memory in map variable M, and function memo_p() requires existanse of global variable M.
One can, of course, just use

kill(M)

by hand but that's not good.

Is it possible to write a function that
-- creates some local variable M with empty map
-- gives that variable M to another function (maybe within "main" function) that recusively calculates it's value using given map
-- returns calculated value
-- exits, thus destroying that map variable

Thank you,
Dmitry.

P.S. Running that code on windows 7 (pari/gp version 2.11.0) with
M=Map();memo_p(10000,3000)
results in pari/gp executable "gp.exe" crush.