# How to select from a list at specific locations

Suppose that a list can be generated for a sum of primes as follows:

g[n_]:= g[n]= Sum[Prime[j], {j, n}];
lst = Table[g[n], {n, 1, 1000}];


Now that a list has been created what is an efficient way to select values at Lucas number positions ? The result should read {2, 10, 17, 58, ...}. I have tried several version of Select,

Select[Range, Extract[ LucasL[#]][ lst[[#]] ] &]
Select[Range, Pick[ lst[[#]], LucasL[#] ] &]


and all lead to empty results.

For context: The calculation process above was/is an attempt to speed up the sum

f[n_]:= f[n]= Sum[Prime[i], {i, LucasL[n]}];
Table[f[n], {n,1,50}]


Any ideas on how to select data from particular positions or how to speed up the calculation of the series would be most helpful.

• lst[[Table[LucasL[n], {n, 1, 10}]]]? Jul 1 at 18:39
• try also lst[[LucasL@Range@10]] or Extract[lst, LucasL[List /@ Range]] or Extract[lst, List /@ LucasL[Range@10]]?
– kglr
Jul 1 at 18:59
• you can also map g on LucasL[Range@10] (that is, g /@ LucasL[Range@10]), instead of generating a larger table and filtering it.
– kglr
Jul 1 at 19:07

Clear["Global*"]

g1[n_] := g1[n] = Sum[Prime[j], {j, n}];

t1 = AbsoluteTiming[
lst1 = Table[g1[n], {n, 1, 1000}];][]

(* 0.142708 *)


The definition of g1 repeatedly calculates identical values of Prime. Using a recursive definition avoids this.

g2 = Prime;
g2[n_] := g2[n] = g2[n - 1] + Prime[n];

t2 = AbsoluteTiming[
lst2 = Table[g2[n], {n, 1, 1000}];][]

(* 0.002815 *)


The second method is about 50 times faster

t1/t2

(* 50.6956 *)


The different definitions give identical results.

lst1 === lst2

(* True *)


To find the maximum value of n

nmax = Floor@NMaxValue[{n, LucasL[n] <= 1000}, n]

(* 14 *)


Then, as pointed out in the comments

lst1[[LucasL@Range@nmax]]

(* {2, 10, 17, 58, 160, 501, 1480, 4438, 13101, 38238, 110364,
316421, 901478, 2549658} *)
`