Nested loops result

后端 未结 3 767
星月不相逢
星月不相逢 2021-01-24 01:03

I really don\'t know how to find out the result of nested loops. For example in the following pseudo-code, I can\'t sort out what will be given at the end of execution. I\'ll b

3条回答
  •  离开以前
    2021-01-24 01:39

    I am getting it something like this :

    n = 1: r = 2
    n = 2: r = 8
    n = 3: r = 20
    n = 4: r = 40
    n = 5: r = 70
    n = 6: r = 112
    n = 7: r = 168
    n = 8: r = 240
    n = 9: r = 330
    n = 10: r = 440
    

    lets say for n = 10,

    r = 2 + 6 + 12 + 20 + 30 + 42 + 56 + 72 + 90 + 110 = 440
    => r = 2(1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 + 55)
    

    Intuitively, I think

    n = sum(n-1) + n * (n + 1).
    

    where

    sum(n-1) = value of r for n-1
    

提交回复
热议问题