Big-O complexity for n + n-1 + n-2 + n-3 + (…) + 1

前端 未结 2 1519
南旧
南旧 2020-12-29 08:05

I was wondering.. what is the complexity of an algorithm that starts with n elements (which I run through doing whatever). I take one element off, I do it again.. I take off

相关标签:
2条回答
  • 2020-12-29 08:09

    The famous mathematician Gauss is said to have found a formula for that exact problem when he was in primary school. And as mentioned by @Henry in the comments it is:

    Source: Wikipedia

    As work is done for every entry, i.e., O(1) is required for each "item". Hence, the problem is in O(n^2).

    Visualisation (also Wikipedia) can be seen as a half filled square:

    0 讨论(0)
  • 2020-12-29 08:13

    To solve the complexity for O(n+n-1+n-2....n times), we need to use Sum for mathematics formula by see this link

    => n+n+n...n times - (1+2+3...n times)
    => n^2- (n^2+n)/2
    

    Complexity will be

    (n^2-n)/2
    
    0 讨论(0)
提交回复
热议问题