This can be done O(n+m) times by running the distributive property of multiplication by adding.
The required amount can be summarized 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 expand the element B Then the series 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 elements from A is a factor of each term in the above series, which can be taken into account to give
(A[0] + A[1] + ... + A[m-1]) * (B[0] + B[1] + ... + B[n-1])
Thus, we can calculate the sum of the elements of both arrays and multiply them together to get the sum of the series.
source share