Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to know, why this is O(n2) for 1+2+3+...+n?

For example, 1+2+3+4 = 4·(4+1)/2 = 10 but 42=16, so how come it's O(n2)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

In Big-O notation you forget about constant factors.

In your example S(n) = 1+2+...+n = n·(n+1)/2 is in O(n2) since you can find a constant number c with

S(n) < c · n2 for all n > n0

(just choose c = 1).
Notice: Big-O notation is an upper bound, i.e. S(n) grows not faster than n2.
Notice also, that S(n) also grows obviously not faster than n3 so it is also in O(n3).

Some additional:

You can also proof the other way around that n2 is in O(S(n)).

n2 < c·S(n) = c·n·(n+1)/2 holds for any c &geq; 2 for all n

So n2 is in O(S(n)). This means both functions grow asymtoticly equal. You can wirt this as S(n) is in Θ(n2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...