0

For finding the sum of n numbers, which is the better option for less time complexity?

  1. using a for loop and iterate throughout the n numbers of an array
  2. using the real equation (n*(n-1))/2

I think that the second one is correct, but it will also depends on the length of the array? Which one is correct here ?

  • 1
    The correctness of the second approach depends on the meaning of "n numbers". If I had 3 numbers that were `0`,`0`, and `0`. The second option wouldn't give the correct answer. The second option is going to be faster in almost all cases, correctness notwithstanding. And if considering asymptotic runtime then the behavior at tiny sizes isn't relevant - the second option is clearly faster for exceedingly large `n`. Addition of `n` numbers taking `O(n)` time, while multiplication of `n` and (approximately) `n` takes `O(log(n)loglog(n))` time. – moreON Feb 18 '21 at 05:19
  • Judging from the answer in https://stackoverflow.com/questions/46505827/what-are-the-relative-cycle-times-for-the-6-basic-arithmetic-operations it appears that on about (1 multiplication + 1 multiplication + 1 substraction + 1 division) => 1 + 1 + 1 + 3 => 6 members the second approach would be faster. Of course, even if you always use the second approach, you'll be losing less than a millisecond for each calculation, not worth checking and load the first approach. – Martheen Feb 18 '21 at 05:26
  • 1
    The second approach is of course more efficient but you need to divide `n` or `n-1` (whichever is the even one) by 2 first to avoid an overflow. – Mo B. Feb 18 '21 at 12:29
  • looping will give time complexity of `O(n)` whereas using formula based approach will give that of `O(1)`. Implementing 2nd in a way to avoid overflow is the only best solution. Also `but it will depend on the length of an array?` Why? That formula is for sum of numbers from `1 2 3 ... n`. You already know what numbers are present in array so you won't need to traverse each element of array using loop. – Akash Dahane Feb 19 '21 at 06:27

0 Answers0