Writing procedures

bongiman's picture

Hi,

I've written the following procedure and seem to have completely forgotten how to code in Maple!!

> restart:
> p:=proc(n,int)
>   local k,s,i;
> for k from 2 to n do
> s[n]:= 2*sum(s[i]*s[n-i],i=1..n-2)+s[n-1]; end do:
> eval(s[n],n=k);
> end:
>
> p(2);p(3);p(4);p(5);p(10);
 

The above code yields results in terms of the expression s[i]. How do get my procedure to actually add it all up. For example p(10) should equal 103049? Many thanks.


          

 

encyclopedia

Your code has a few peculiarities and obvious errors that make it hard to follow what you are trying to do, but the Encyclopedia of Integer Sequences shows a sequence whose tenth term is 103049, and one of the  suggested formulae is quite close to the one you seem to be trying to use. 

Based on this, maybe you want the following:

 

p:=proc(n::posint)
local k,s,i;
s[1]:=1;
s[2]:=1;
for k from 2 to n do
s[k]:=2*sum(s[i]*s[k-i],i=1..k-2)+s[k-1]; od;
s[n];
end;

 

p(10);

 

 

bongiman's picture

Many thanks Alex

I was so close but so far! :)

acer's picture

add

`add` is faster than `sum` for this sort of thing. It was about 2.5 times faster to compute p(2000) using `add` rather than `sum`, for example.

Writing a truly recursive procedure `s`, with option remember, is also faster than the above `sum` code (but not as fast as with `add`). But it could help, if you intend on computing some sorts of very long sets of increasing values with it.

s := proc(n)
local k;
option remember;
    if n = 1 or n = 2 then return 1
    else for k from 2 to n do
            s(k) := 2*add(s(i)*s(k - i), i = 1 .. k - 2) + s(k - 1)
        end do
    end if;
    s(n)
end proc:

So, once s(2000) is computed then s(1000) is computed near instantaneously, as it only requires a remember-table lookup.

I didn't bother considering whether there is any closed form of any of this.

acer

Robert Israel's picture

closed form

According to the OEIS entry, there is a "closed form", if you count 2F1 hypergeometric functions:

p(n) = hypergeom([2-n, n+1], [2], -1)

 

 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
}