If we have two arrays say A=[1,2,3,4]
and B=[1,2,3]
we need to find the sum 1*1+1*2+1*3+2*1+2*2+2*3+3*1+3*2+3*3+4*1+4*2+4*3
,i.e sum of product of all possible pairs in both arrays which may be of different lenghts.
Of course we can do it in O(n^2)
but is there any efficient way to do it ?
Thanks.
Also both the arrays have integers in the range 1..m
and 1..n
respectively
The product of two matrices can be computed by multiplying elements of the first row of the first matrix with the first column of the second matrix then, add all the product of elements. Continue this process until each row of the first matrix is multiplied with each column of the second matrix.
You can find the product of all elements of the array using iteration/loops by following the approach below: Initialize a variable result (with a value of 1) to store the product of all elements in the array. Iterate through the array and multiply each element of the array with the result. Finally, return the result.
This can be done in O(n+m)
time by levying the distributive property of multiplication over addition.
The required sum can be generalized as follows:
(A[0]*B[0] + A[1]*B[0] + ... + A[m-1]*B[0]) + (A[0]*B[1] + A[1]*B[1] + ... + A[m-1]*B[1]) + ... + (A[0]*B[n-1] + A[1]*B[n-1] + ... + A[m-1]*B[n-1])
Note that in each partial sum, we can factor out the element of B
. The series then simplifies to
(A[0] + A[1] + ... + A[m-1]) * B[0] + (A[0] + A[1] + ... + A[m-1]) * B[1] + ... + (A[0] + A[1] + ... + A[m-1]) * B[n-1]
Note that the sum of all the elements in A
is a factor of each term in the above series, which can be factored out to give
(A[0] + A[1] + ... + A[m-1]) * (B[0] + B[1] + ... + B[n-1])
We can thus compute the sum of elements of both the arrays and multiply them together to obtain the sum of the series.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With