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

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

    n(n+1)/2 is the quick way to sum a consecutive sequence of N integers (starting from 1). I think you're confusing an algorithm with big-oh notation!

    If you thought of it as a function, then the big-oh complexity of this function is O(1):

    public int sum_of_first_n_integers(int n) {
      return (n * (n+1))/2;
    }
    

    The naive implementation would have big-oh complexity of O(n).

    public int sum_of_first_n_integers(int n) {
      int sum = 0;
      for (int i = 1; i <= n; i++) {
        sum += n;
      }
      return sum;
    }
    

    Even just looking at each cell of a single n-by-n matrix is O(n^2), since the matrix has n^2 cells.

提交回复
热议问题