2
$\begingroup$

In this code I do Sum over r and x

rgt[rf_, n_, m_] := ParallelSum[x r, {r, 0, rf, n}, {x, 1, 5, m}]  

then I want to get the results for different rf as follows

Table[rgt[rf,1,1],{rf,6,20,2}]//AbsoluteTiming
{0.077568,{315,540,825,1170,1575,2040,2565,3150}}  

Note that at each rf the Sum over r starts always from 0 but this can be avoided if I can just add the Sum of the earlier step to the next one. How can I do that?

$\endgroup$
2
$\begingroup$

Outer product approach:

rgt[rf_, n_, m_] := Accumulate@Total[
   Outer[Times, Range[0, rf, n], Range[1, 5, m]],
   {2}
   ]

rgt[20, 1, 1][[7 ;; ;; 2]] // AbsoluteTiming

{0.000026, {315, 540, 825, 1170, 1575, 2040, 2565, 3150}}

$\endgroup$
2
  • $\begingroup$ what if I have a general function, say (Sqrt[x] + 2 r)/(r + 1)? $\endgroup$ Sep 5 '20 at 18:00
  • 1
    $\begingroup$ @HD2006 Just put it in where Times is. $\endgroup$
    – C. E.
    Sep 5 '20 at 18:02

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.