Efficient algorithm to calculate the sum of all k-products

前端 未结 6 1931
青春惊慌失措
青春惊慌失措 2021-02-06 04:49

Suppose you are given a list L of n numbers and an integer k. Is there an efficient way to calculate the sum of all products of

6条回答
  •  北海茫月
    2021-02-06 05:36

    Algebraically, for k=2 just take the sum of the elements of L, square it, and subtract the sum of the squares of L. That is:

    int sum = 0;
    int sqSum = 0;
    for (int i=0; i

    In your example, what you are computing is this

    (1 + 3 + 4 + 6)^2 - (1^2 + 3^2 + 4^2 + 6^2) = 1*3 + 1*4 + 1*6 + 3*4 + 3*6 + 4*6
    

    This should give you a hint for how to proceed in general.

提交回复
热议问题