I think RecurrenceTable
deserves justice as a very efficient way to tabulate solutions of the recurrence equations.
Compare procedural approach with no dynamic programming used:
In[214]:= Block[{u, A},
u[1] := 1; u[2] := 2;
u[3] := 3;
u[y_] := -u[y - 3] + 3*u[y - 2] + 2*u[y - 1];
A = Table[u[k], {k, 1, 25}];
Total[Select[A, EvenQ]]] // AbsoluteTiming
Out[214]= {4.617608, 7856903616}
to the use of RecurrenceTable
, where all that is needed is to define the equation:
In[215]:=
Select[RecurrenceTable[{u[1] == 1, u[2] == 2, u[3] == 3,
u[n] == -u[n - 3] + 3 u[n - 2] + 2 u[n - 1]}, u[n], {n, 1, 25}],
EvenQ] // Total // AbsoluteTiming
Out[215]= {0., 7856903616}
Also, it is worth pointing out that any linear recurrence equation of rank $r$ evaluated $\bmod p$ must be periodic, due to the recurrence relation and the finiteness of the state space. Indeed, our system turns out to have period of 7:
In[217]:= Partition[
Mod[RecurrenceTable[{u[1] == 1, u[2] == 2, u[3] == 3,
u[n] == -u[n - 3] + 3 u[n - 2] + 2 u[n - 1]}, u[n], {n, 1, 32}],
2], 7]
Out[217]= {{1, 0, 1, 1, 1, 0, 0},
{1, 0, 1, 1, 1, 0, 0},
{1, 0, 1, 1, 1, 0, 0},
{1, 0, 1, 1, 1, 0, 0}}
Thus $u_{7m+2}$, $u_{7m+5}$ and $u_{7m+6}$ are even.
We can now use the symbolic power of Mathematica
to work out the recurrence relation for sums $v^{(2)}_m = \sum_{k=0}^{m} u_{7k+2}$, $v^{(5)}_m = \sum_{k=0}^{m} u_{7k+5}$ and $v^{(6)}_m = \sum_{k=0}^{m} u_{7k+6}$:
For example:
In[223]:= Sum[
DifferenceRoot[
Function[{u, n}, {u[n + 3] == -u[n] + 3 u[n + 1] + 2 u[n + 2],
u[1] == 1, u[2] == 2, u[3] == 3}]][7 k + 2], {k, 0, m}]
Out[223]=
DifferenceRoot[
Function[{y, n}, {-y[n] + 6318 y[1 + n] -
4544 y[2 + n] - 1774 y[3 + n] + y[4 + n] == 0,
y[0] == 0, y[1] == 2, y[2] == 2148, y[3] == 3817822}]][1 + m]
Now, evaluation for any $m$ is just a matter of substitution:
In[224]:= % /. m -> 20
Out[224]= \
118640843309870276692961346051090397680399199522287919469464837082
Working out the solution for $v^{(5)}_m$ and $v^{(6)}_m$ is an easy exercise.
u[n]
terms, i.e. up to infinity ? $\endgroup$u
to speed things up. Just change the first part of your code to:u[1] = 1; u[2] = 2; u[3] = 3; u[y_] := u[y] = -u[y - 3] + 3*u[y - 2] + 2*u[y - 1];
$\endgroup$Total@A
. $\endgroup$