Big O, what is the complexity of summing a series of n numbers?

后端 未结 10 740
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 01:16

I always thought the complexity of:

1 + 2 + 3 + ... + n is O(n), and summing two n by n matrices would be O(n^2).

But today I read from a textbo

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 01:55

    You are confusing complexity of runtime and the size (complexity) of the result.

    The running time of summing, one after the other, the first n consecutive numbers is indeed O(n).1

    But the complexity of the result, that is the size of “sum from 1 to n” = n(n – 1) / 2 is O(n ^ 2).


    1 But for arbitrarily large numbers this is simplistic since adding large numbers takes longer than adding small numbers. For a precise runtime analysis, you indeed have to consider the size of the result. However, this isn’t usually relevant in programming, nor even in purely theoretical computer science. In both domains, summing numbers is usually considered an O(1) operation unless explicitly required otherwise by the domain (i.e. when implementing an operation for a bignum library).

提交回复
热议问题