You are confusing the complexity of computing 1 + 2 + ... + N
(by summing) with the result of computing it.
Consider the cost function f(N) = 1 + 2 + ... + N
. That simplifies to N(N + 1)/2
, and has the complexity O(N^2)
.
(I expect that you learned that sum in your high school maths course. They may even have even taught you how to prove it ... by induction.)
On the other hand, the algorithm
public void sum(int n){
int sum = 0;
for(int i = 1; i <= n; i++){
sum += i;
}
print(sum);
}
computes 1 + 2 + ... + N
by performing N
additions. When do a full analysis of the algorithm taking into account all of the computation, the cost function will be in the complexity class O(N)
.
But I can also compute 1 + 2 + ... + N
with a simpler algorithm that makes use of our match knowledge:
public void sum(int n){
print(n * (n + 1) / 2);
}
This alternative algorithm's cost function is O(1)
!!!
Lesson: don't confuse an algorithm's cost function with its result.