I am answering the question as posted, where $0\le a_i <k$, not the original coding challenge, where the constraint is $l\le a_i\le r$. However, using the transformation $a_i\to a_i-l$, you should be able to turn the latter problem into the former.
Suppose first that $k=3j$ is a multiple of three. The number of ways to choose numbers $a_i$ so that $-1<a_i<k$ is $(3j)^n$. I claim that exactly one third of these solutions have $\sum a_i$ a multiple of $3$. Indeed, if you break solutions into triplets like
$$
(3i,a_2,a_3,\dots,a_n),(3i+1,a_2,a_3,\dots,a_n),(3i+2,a_2,a_3,\dots,a_n)
$$
then exactly one solution in each triplet has a sum which is a multiple of $3$. Therefore, the number of vectors is
$$
\frac13 k^n
$$
The problem is easy when $k=3j$. What about when $k=3j+1$? A similarly argument shows that among vectors $(a_1,\dots,a_n)$ where at least one coordinate is unequal to $3j$, exactly one third of them have sum which is a multiple of $3$. The only remaining vector is where every $a_i=3j$, whose sum $3$ divides. Therefore, the number of vectors is
$$
\frac13[k^n-1]+1
$$
Note that these numbers can be computed pretty much instantly, no recursion needed!
Finally, the hardest case is when $k=3j+2$. Among the $k^n-2^n$ solutions where at least one $a_i$ is less than $3j$, exactly one third of these have sum a multiple of $3$. The remaining $2^n$ vectors have coordinates all of the form $3j+b$, where $b\in \{0,1\}$. Furthermore, the sum will be a multiple of three if and only if the number of $i$ for which $a_i=3j+1$ is a multiple of $3$. So the question becomes...
Given a number $n$, how many of the $2^n$ subsets of $\{1,2,\dots,n\}$ have a size which is a multiple of $3$?
For that, I point you to How do I count the subsets of a set whose number of elements is divisible by 3? 4?.