Big O notation for summation function

2.7k Views Asked by At

May be I am missing something very simple but I am finding it hard to understand why Big O for summation is O(n^2). I know that Big O for summation comes from fact that sum(1 to n) = n(n+1)/2. But if we write a simple sum function, it will be something like

sum = 0
for i goes from 1 to n
  sum += i
return sum

The above has O(n). So why we say summation has O(n^2). Apologies if this is too simple.

1

There are 1 best solutions below

0
On BEST ANSWER

Maybe I have misunderstood, but it seems to me that you are mixing up two different questions.

The number of steps required to compute a sum of $n$ terms is $O(n)$.

The final result of adding the numbers $1$ to $n$ is $\frac12n(n+1)$, which is $O(n^2)$.