3

If you have an array and you add 5 to every element, what would you say this runs in? Obviously if it goes over all the elements in the array then it should by default be O(n). However, since adding an integer value is O(1), could we say the entire function is O(1) since your just repeating an O(1) addition many times?

Thanks

Michael
  • 61
  • 6
  • 2
    1 + 1 + 1 .... + 1 (n times) = n. Why does this seem puzzling? All computation is a series of O(1) operations, but it doesn't all collapse to O(1) – John Coleman May 11 '17 at 13:21
  • repeating same thing of some `complexity x` n times has total complexity of O(x*n) – sameerkn May 11 '17 at 13:23
  • What is `n`? The size of the array? Or does your array have constant size, and `n` is something else? – Bergi May 11 '17 at 13:34
  • Are you sure that adding two integer values is `O(1)`? Even for arbitrarily large integers? What if we say `m` is the number of digits of the numbers? – Bergi May 11 '17 at 13:36

2 Answers2

4

Doing an O(1) operation O(n) times has an algorithmic complexity of O(1 * n) = O(n)

SirGuy
  • 10,660
  • 2
  • 36
  • 66
3

According to your theory, any function would be O(1) since they are repeating a O(1) operation more or less. Repeating an O(1) operation constant times - which means the repeated times has nothing to do with n - is still O(1). However repeating an O(1) operation x times when x contains n isn't O(1).

e.g. repeating an operation 30000 times is still O(1), 1/2n+30000 is O(n), 3n^3+2n^2+2 is O(n^3). You take the highest degree one and remove the coefficient.

Richard Yan
  • 1,276
  • 10
  • 21
  • In fact every function *is* in `O(1)` as soon as we limit the size of the input to some arbitrary maximum, or just don't measure that unlimited property :-) – Bergi May 11 '17 at 13:33
  • As long as your input is constant, that's probably true. However, when the input is varying I don't think the statement holds up, since the time complexity of a algorithm is related to the size of the problem, isn't it? As long as the input is an indicator of the size of the problem, it's not O(1). – Richard Yan May 11 '17 at 13:35
  • Yes, that's exactly what I mean, it all depends on how the problem is stated and how we indicate its size. We for example usually ignore to take into account the length of each number in the array, and consider addition to be constant. – Bergi May 11 '17 at 13:39