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

后端 未结 10 754
伪装坚强ぢ
伪装坚强ぢ 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:53

    There really isn't a complexity of a problem, but rather a complexity of an algorithm.

    In your case, if you choose to iterate through all the numbers, the the complexity is, indeed, O(n).

    But that's not the most efficient algorithm. A more efficient one is to apply the formula - n*(n+1)/2, which is constant, and thus the complexity is O(1).

提交回复
热议问题