Reputation: 1669
I want to implement an algorithm which takes the first element and build the sum like that:
In fact, I am taking the 1 element and build the sum, then the 1st and the 2nd and build the sum, then the 1st, 2nd and 3rd and build the sum etc.
I tried:
for (int l = 0; l < valueList.size(); l++) {
double result = ((valueList.get(0) + valueList.get(l)) * (l + 1))/2;
resultList.add(result);
}
However this does not seem to work. How to implement such an algorithm?
I would appreciate your answers!
Upvotes: 0
Views: 108
Reputation: 7868
That algorithm is similar to the factorial function:
f(x) = x + f(x-1)
You could implement that recursively:
public int sum(int x) {
if (x == 0) {
return 0;
}
return x + sum(x - 1);
}
or iteratively:
int sum = 0;
for (int i = x; i > 0; i--) {
sum += i;
}
Upvotes: 0
Reputation: 7717
try this
for (int l = 0; l < valueList.size(); l++) {
double result = ((l>0) ? resultList.get(l-1) : 0) + valueList.get(l);
resultList.add(result);
}
Upvotes: 1