user2051347
user2051347

Reputation: 1669

Summing up all previous numbers

I want to implement an algorithm which takes the first element and build the sum like that:

enter image description here

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

Answers (2)

Markus Malkusch
Markus Malkusch

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

venergiac
venergiac

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

Related Questions