I have a double[] of huge size. (Ex : Eg.double[] array = new double[] {2.0, 3.1, 4.2, 8.9, 10.11, ........}
)
I want to get the sum of all the elements of that array at once. (Without using a loop).
Do you have any idea to do this?
No, you can't calculate the sum of a list of values in one step. Even if there was an API method or some library that offered a sum function, it would use loops internally. The complexity of the sum algorithm is O(n) (for single CPUs).
A way out could be using parallel computing, but that's a theoretical approach to answer your question. You'd need at least as many CPUs as array cells to calculate the sum in on step. (Or one fictional CPU with as many FP registers as array values).
Before you start looking at API's of Java or other libraries:
public static double sum(double...values) {
double result = 0;
for (double value:values)
result += value;
return result;
}
Usage:
double sum = sum(array); // this is in your main code -> no loop (visible)
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