Determining as a function of n how often the statement incrementing the variable count is performed

后端 未结 3 679
时光取名叫无心
时光取名叫无心 2021-01-19 17:16

Ok so I\'m new to analyzing algorithms and would really appreciate any helpful tips that can be shared on how to go about this. I am trying to determine how many times count

相关标签:
3条回答
  • 2021-01-19 17:56

    Here you go:

    count = n * (n + 1) / 2

    0 讨论(0)
  • 2021-01-19 17:57

    The aim of this type of exercise is to teach how to you analyze it on paper instead of running it on a machine. But let's look at the pattern:

    • The outer loop will run a total of n times
    • The inner loop will run between 1 to n times depend on what i is at the time. But you know that on average this will run (n+1)/2 times.
    • Thus count = n(n+1)/2), which is O(n^2)

    See arithmetic series

    Update: As requested - why the inner loop is (n+1)/2:

    The outer loop will increment i between 1 and n. So on each iteration of the outer loop, the inner loop will "loop" one more than than it did previously.

    Thus the inner loop will iterate this number of times:

    • 1 + 2 + 3 + ... + n

    So we can do something clever and pair up :

    • n with 1: (n + 1) = n + 1
    • n-1 with 2: (n - 1) + 2 = n + 1
    • n-2 with 3: (n - 2) + 3 = n + 1
    • ...

    And since we paired these up, we have n/2 such pairs:

    • So the sum of 1 + 2 + ... + n is ( (n+1) * (n/2) ).
    • So the average is ( (n+1) * (n/2) ) / n = (n+1)/2

    (Visualize it as you are writing 1 + 2 + 3 + ... + n on a long strip of paper, and you fold it in half.)

    I would also highly recommend reading this famous story about Karl Friedrich Gauss so you'll always remember how to sum arithmetic series =)

    0 讨论(0)
  • 2021-01-19 17:58

    1

    1+2 = 3

    1+2+3 = 6

    1+2+3+4 = 10

    1+2+3+4+5 = 15

    It is only me who sees the pattern? :-)

    0 讨论(0)
提交回复
热议问题