2
$\begingroup$

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[10], Extract[ LucasL[#]][ lst[[#]] ] &]
Select[Range[10], 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.

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

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

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

(* 0.142708 *)

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

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

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

(* 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} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.