Suppose I have an array {1, 2, 5, 4}
and m = 3
.
I need to find:
1*2*5 + 1*2*4 + 1*5*4 + 2*5*4
i.e Sum of multipli
I came up with the same problem. I found the solution via Vieta's Algorithm as well. I tweaked the algorithm not the calculate the coefficient of the polynomial which are not needed. The complexity is O(N*M). I looked into DFTs and FFTs but if M is small enough, this method will be even faster than Fast Fourier Transformation algorithms. This is java btw.
public BigInteger sumOfCombMult(Integer[] roots, int M)
{
if (roots.length < M)
{
throw new IllegalArgumentException("size of roots cannot be smaller than M");
}
BigInteger[] R = new BigInteger[roots.length];
for (int i = 0; i < roots.length; i++)
{
R[i] = BigInteger.valueOf(roots[i]);
}
BigInteger[] coeffs = new BigInteger[roots.length + 1];
coeffs[0] = BigInteger.valueOf(roots[0]);
int lb = 0;
for (int i = 1; i < roots.length; i++)
{
lb = Math.max(i - M, 0);
coeffs[i] = R[i].add(coeffs[i - 1]);
for (int j = i - 1; j > lb; j--)
{
coeffs[j] = R[i].multiply(coeffs[j]).add(coeffs[j - 1]);
}
if (lb == 0)
{
coeffs[0] = coeffs[0].multiply(R[i]);
}
}
return coeffs[roots.length - M];
}