Computing the sum of integers from 1 to N

suggest change

The following method computes the sum of integers from 1 to n for a positive n. sum(0) returns 0, and a negative argument returns that argument unchanged.

public int sum(final int n) {
    if (n > 0) {
        return n + sum(n - 1);
    } else {
        return n;
    }
}

This method is O(n) and can be rewritten as a loop. The JVM does not apply tail-call optimization, so this version still uses O(n) stack frames. The closed form n * (n + 1) / 2 computes the same sum in O(1) operations. The int result overflows for large n.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents