Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding the elements of a double[] array without using a loop in java

Tags:

java

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?

like image 791
Namalak Avatar asked Nov 04 '10 07:11

Namalak


1 Answers

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)
like image 99
Andreas Dolk Avatar answered Oct 21 '22 04:10

Andreas Dolk