Re: How to simplify this code with variable number of

*To*: mathgroup at smc.vnet.net*Subject*: [mg124287] Re: How to simplify this code with variable number of*From*: DrMajorBob <btreat1 at austin.rr.com>*Date*: Mon, 16 Jan 2012 17:05:13 -0500 (EST)*Delivered-to*: l-mathgroup@mail-archive0.wolfram.com*References*: <201201150951.EAA19677@smc.vnet.net>*Reply-to*: drmajorbob at yahoo.com

It's unclear what "for a[g]=a[g-1]+1 to 2g-1 do" might mean (for instance), but I'll make a guess or two. Possibly you mean a[g] = a[g-1] + Sum[i,{i,1,2 g - 1,2} or a[g] = a[g-1] + Sum[i,{i,1,2 g - 1} If so, both sums are simple: Sum[i, {i, 1, 2 g - 1, 2}] g^2 Sum[i, {i, 1, 2 g - 1}] g (-1 + 2 g) Defining a recursive function is also simple. For instance, Clear[a] a[0] = 0; a[k_] := a[k - 1] + k^2 a[120] 583220 If I try a larger value, problems may occur: a[1000] $RecursionLimit::reclim: Recursion depth of 256 exceeded. >> But that can be fixed: Clear[a] a[0] = 0; a[k_] := a[k] = a[k - 1] + k^2 Do[a[k], {k, 1000}] a[1000] 333833500 a memorizes its values as they are calculated, and Do calculates them in order, hence recursion never has to go back more than one index. If you want some index to be different than others, as implied by "###some computations here###", then it might be: g = 1000; Clear[a] a[0] = 0; a[g] := a[g - 1] + whatever; a[k_] := a[k] = a[k - 1] + k^2 Do[a[k], {k, 1000}] a[1000] 332833500 + whatever Bobby On Sun, 15 Jan 2012 03:51:29 -0600, Rex <aoirex at gmail.com> wrote: > Considering an array a[i], i=0,1,...,g, where g could be any given > number, and a[0]=1. > > for a[1]=a[0]+1 to 1 do > for a[2]=a[1]+1 to 3 do > for a[3]=a[2]+1 to 5 do > ...... > for a[g]=a[g-1]+1 to 2g-1 do > ###some computations here### > > The problem is that everytime we change the value of g, we need to > modify the code, those loops above. So this is not a good code. > > Any advice would be greatly appreciated. > -- DrMajorBob at yahoo.com

**References**:**How to simplify this code with variable number of nesting loops?***From:*Rex <aoirex@gmail.com>