Sum of multiplication of all combination of m element from an array of n elements

后端 未结 3 934
走了就别回头了
走了就别回头了 2020-12-03 13:06

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

3条回答
  •  抹茶落季
    2020-12-03 13:38

    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];
    }
    

提交回复
热议问题