You need to use a little math. Suppose you have 3 values, for example your example, but call them A , B and C
To get the sum of products, you need to calculate:
Result3 = A + B + C + A*B + A*C + B*C + A*B*C = A + B + A*B + (1 + A + B + A*B) * C
Now, if we first calculate A + B + A*B , calling it Result2 , you will get:
Result2 = A + B + A*B Result3 = Result2 + (1 + Result2) * C
And we repeat that
Result2 = A + (1 + A) * B Result1 = A Result2 = Result1 + (1 + Result1) * B
Do you see the template? Let use this with 4 values:
Result4 = A + B + C + D + A*B + A*C + A*D + B*C + B*D + C*D + A*B*C + A*B*D + A*C*D + B*C*D + A*B*C*D = A + B + C + A*B + A*C + B*C + A*B*C + (1 + A + B + C + A*B + A*C + B*C + A*B*C) * D = Result3 + (1 + Result3) * D
Summary:
Result1 = A Result2 = Result1 + (1 + Result1) * B Result3 = Result2 + (1 + Result2) * C Result4 = Result3 + (1 + Result3) * D
As a code, this is:
private static long sumProduct(int... input) { long result = 0; for (int value : input) result += (result + 1) * value; return result; }
Only one iteration, therefore O (n).
Test
System.out.println(sumProduct(2, 3)); System.out.println(sumProduct(2, 3, 5)); System.out.println(sumProduct(2, 3, 5, 7));
Exit
11 71 575
UPDATE
The code can also be executed using Java 8 Streams with a Lambda expression using IntStream.of(int...) or Arrays.stream(int[]) (they do the same).
Andreas
source share