Design algorithm for an expression with multiple sums

38 Views Asked by At

I am trying to write a code to compute the below math formula:

$$A(N,M,f)=\sum_{{n_1}=0}^N\sum_{n_2=0}^{n_1}\cdots\sum_{n_{M-1}}^{n_{M-2}}f(n_1,n_2,...,n_{M-1})$$

When $M$ is small, we can use several "for-loops", i.e., $M=3$,

for $n_1=0:N$

for $n_2=0:n_1$

compute $f(n_1,n_2)$

end

end

However, when $M$ is very large (e.g., $M=1000$), it is not a good idea to write 1000 "for-loops". Does anyone have any suggestion please? Thank you.