Computing the sum of integers from 1 to N
suggest changeThe 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents