gpt4 book ai didi

loops - 一个与嵌套循环相关的谜题

转载 作者:行者123 更新时间:2023-12-04 10:40:50 25 4
gpt4 key购买 nike

对于给定的输入 N,所包含的语句执行多少次?

for i in 1 … N loop
for j in 1 … i loop
for k in 1 … j loop
sum = sum + i ;
end loop;
end loop;
end loop;

任何人都可以想出一个简单的方法或公式来做到这一点。请解释。

最佳答案

  • 首先,我写了一个C代码来生成sum:

  • int main(){
    int i =0, k =0, j =0, n =0;
    int N =0;
    int sum =0;
    N =10;
    for (n=1; n <= N; n++){
    // unindented code here
    sum =0;
    for (i=1; i<=n; i++)
    for (j=1; j<=i; j++)
    for (k=1; k<=j; k++)
    sum++;

    printf("\n N=%d sum = %d",n, sum);
    }
    printf("\n");
    }

  • N=1 to N=10 的简单编译和生成结果:
  • $ gcc sum.c $ ./a.out
     N=1  sum = 1
    N=2 sum = 4
    N=3 sum = 10
    N=4 sum = 20
    N=5 sum = 35
    N=6 sum = 56
    N=7 sum = 84
    N=8 sum = 120
    N=9 sum = 165
    N=10 sum = 220
  • 然后,尝试用一些图表探索 How this works?:

    对于, N=1 :

  • i<=N,     (i=1)       
    |
    j<=i, (j=1)
    |
    k<=j, (K=1)
    |
    sum=0. sum++ ---> sum = 1


    即 (1) = 1

    对于 N=2 :

    i<=N,     (i=1)-------(i=2)
    | |-----|-----|
    j<=i, (j=1) (j=1) (j=2)
    | | |----|----|
    k<=j, (K=1) (K=1) (K=1) (K=2)
    | | | |
    sum=0, sum++ sum++ sum++ sum++ --> sum = 4


    即 (1) + (1 + 2) = 4

    对于 N=3 :

    i<=N,     (i=1)-------(i=2)--------------------(i=3)
    | |-----|-----| |---------|-------------|
    j<=i, (j=1) (j=1) (j=2) (j=1) (j=2) (j=3)
    | | |----|----| | |----|----| |-----|-----|
    k<=j, (K=1) (K=1) (K=1) (K=2) (K=1) (K=1) (K=2) (K=1) (K=2) (K=3)
    | | | | | | | | | |
    sum=0, sum++ sum++ sum++ sum++ sum++ sum++ sum++ sum++ sum++ sum++
    --> sum = 10


    即 (1) + (1 + 2) + ( 1 + 2 + 3 ) = 10
    N = 1, (1)    = 1                                           

    N = 2, (1) + (1 + 2) = 4

    N = 3, (1) + (1 + 2) + (1 + 2 + 3) = 10

    N = 4, (1) + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) = 20

    N = 5, (1) + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4 + 5) = 35

    最后,我可以理解三个循环中 N 的总和是:

    (1) + (sum 0f 1 to 2) + ... + (sum of 1 to (N-2)) + (sum of 1 to (N-1) ) + (sum of 1 to N)

    或者我们可以写成:

    => (1) + (1 + 2) + ...+ (1 + 2 +....+ i) + ... + (1 + 2 + ....+ N-1) + (1) + 2 + ....+ N)

    => ( N * 1 ) + ( (N-1) * 2) + ( (N-2) * 3) +...+ ( (N -i+1) * i ) +... + ( 1 * N)

    您可以引用这里进行简化计算: (I asked HERE )


    [ 你的回答 ]
    = ( ((N) * (N+1) * (N+2)) / 6 )
    而且,我认为它是正确的。我检查如下:
    N = 1,    (1 * 2 * 3)/6  = 1

    N = 2, (2 * 3 * 4)/6 = 4

    N = 3, (3 * 4 * 5)/6 = 6

    N = 4, (4 * 5 * 6)/6 = 10

    N = 5, (5 * 6 * 7)/6 = 35

    此外,该算法的复杂度为 O(n3)

    编辑 :

    下面的循环也有相同的计数,即 = ( ((N) * (N+1) * (N+2)) / 6 )
    for i in 1 … N loop
    for j in i … N loop
    for k in j … N loop
    sum = sum + i ;
    end loop;
    end loop;
    end loop;

    关于loops - 一个与嵌套循环相关的谜题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621550/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com