简体   繁体   English

该循环执行多少次

[英]how many times will this loop execute

I was just wondering how many times a nested loop like this would run 我只是想知道这样的嵌套循环会运行多少次

int sum = 0;
for(int i = 0; i < total; i++) {
    for(int j = i + 1; j < total; j++) {
        for(int k = j; k < total; k++) {
            sum++;    
        }
    }
}
System.out.println(sum);

I can easily see the output of sum, but I would like to be able to mathematically calculate the total of sum with any number for total . 我可以很容易地看到总和的输出,但我希望能够用数学计算总的sum与任意数量的total

It needs only a little bit knowledge of programming.Actually logic that is running behind is only computational kind of thing. 它只需要一点编程知识。实际上,落后的逻辑只是计算方面的事情。 let's say: 比方说:

total=10,sum=0

- when i is 0: -当我为0时:

That time j is initialised with 1(i+1) and k as well. 那个时间j也用1(i + 1)和k初始化。 So k will lead us to execute the loop 9 times and and as j is incremented ,it will lead us to execute sum statement 8 times and 7 times and further 6 times till 1 time. 因此k将导致我们执行9次循环,并且随着j的增加,它将导致我们执行sum语句8次,7次,再执行6次直到1次。 (9+8+7+6+5+4+3+2+1=45 times.) (9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45次。)

- when i is 1: -当我1:

That time j is initialised with 2 and k as well.So sum statement is going to execute 8 times and then 7 times and then 6 times till 1. (8+7+6+5+4+3+2+1=36 times). 那个时间j也用2和k初始化。所以sum语句将执行8次,然后执行7次,然后执行6次直到1。(8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36次)。

- when i is 2: -当我2岁时:

Same thing happens repeatedly but starting with difference number ,so this time (7+6+5+4+3+2+1=28) 相同的事情反复发生,但是以不同的数字开头,所以这次(7 + 6 + 5 + 4 + 3 + 2 + 1 = 28)

  • So this sequence continues until there is significance of occuring the condition with trueness. 因此,此序列一直持续到有意义地真实发生条件为止。 This happens till i is 9. 这一直发生到我9岁为止。

So the final answer is 1+3+6+10+15+21+28+36+45=165. 所以最终答案是1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 = 165。

The first iteration of the middle loop adds 中间循环的第一次迭代添加

total-1 + total-2 + ... + 1 

to the sum. 总和。

The second iteration of the middle loop adds 中间循环的第二次迭代添加

total-2 + total - 3 + ... + 1 

to the sum 总和

The last iteration of the middle loop adds 中间循环的最后一次迭代添加

1

to the sum. 总和。

If you sum all of these terms, you get 如果将所有这些条件加起来,您将得到

(total - 1) * 1 + (total - 2) * 2 + (total - 3) * 3 + ... + 2 * (total - 2) + 1 * (total - 1)

It's been a while since I studied math, so I don't remember if there's a simpler formula for this expression. 自从我学习数学以来已经有一段时间了,所以我不记得这个表达式是否有一个更简单的公式。

For example, if total is 10, you get: 例如,如果总数为10,则得到:

9 * 1 + 8 * 2 + 7 * 3 + 6 * 4 + 5 * 5 + 4 * 6 + 3 * 7 + 2 * 8 + 1 * 9 =
9 + 16 + 21 + 24 + 25 + 24 + 21 + 16 + 9 = 
165

TL;DR TL; DR

The loop will be executed for ((total ^ 3) - total) / 6 times and hence that will be the value of sum at the end of the loop. 该循环将执行((total ^ 3) - total) / 6次,因此它将是循环结束时sum的值。


int sum = 0;
for(int i = 0; i < total; i++) { 
    for(int j = i + 1; j < total; j++) {
        for(int k = j; k < total; k++) {
            sum++;    
        }
    }
}

It is easy to see that the outer loop runs for a total times. 可以很容易地看出,外循环运行了total次数。 The second loop is the trickier one 第二个循环比较棘手

Let's try to work this out 让我们尝试解决这个问题

i = 0 , j runs from 1..total - 1 i = 0j1..total - 1

i = 1 , j runs from 2..total - 1 i = 1j2..total - 1

i = 2 , j runs from 3..total - 1 i = 2j3..total - 1

... i = total - 2 , j runs from total - 1 ..total - 1 (will only run once) ... i = total - 2jtotal - 1 ..total - 1 (仅运行一次)

i = total - 1 , inner loop does not execute as the loop termination condition is true. i = total - 1 ,因为循环终止条件为true,所以不执行内部循环。

The third loop is dependent on the second inner loop - k runs from j..total - 1 第三个循环取决于第二个内部循环kj..total - 1运行

Let us take total as 6 让我们合计为6

j runs from 1..5 -> k runs for 5 times ( j = 1 ) + 4 times( j = 2 ) + 3 times( j = 3 )+ 2 times( j = 4 ) + 1 time( j = 4 ) j1..5运行-> k运行5次( j = 1 )+ 4次( j = 2 )+ 3次( j = 3 )+ 2次( j = 4 )+ 1次( j = 4

(Showing a minified version for others) (为其他人显示缩小版)

2..5 -> 4+3+2+1
3..5 3+2+1
4..5 2+1
5..5 1

Which is 哪一个

1 + 2 + 3 + 4 + 5+
1 + 2 + 3 + 4 + 
1 + 2 + 3 +
1 + 2 +
1

Generally, 通常,

1 + 2 + 3 + .. n +
1 + 2 + 3 +..n - 1+
1 + 2 + 3 +..n - 2+
1 + 2 + 3 +
1 + 2 +
1

This boils down to the sum n * (n - 1)) / 2 归结为n * (n - 1)) / 2

For all values of n ranging from 1 to total 对于所有 n (从1 to total

This can be verified with the below 可以通过以下方式验证

int res = 0;
for (int i = 1; i <= total; i++) {
    res += (i * (i - 1))/2;
}

res will be equal to your sum . res将等于您的sum

Mathematically, the above is 数学上,上面是

((total ^ 3) - total) / 6

Derivation: 派生:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

References: 参考文献:

Sums of the First n Natural Numbers 前n个自然数的和

Sum of the Squares of the First n Natural Numbers 前n个自然数的平方和

outermost loop runs 'total' number of times. 最外面的循环运行“总数”次。

for each outer loop , middle loop runs 'total-i' times. 对于每个外部循环,中间循环运行“总计-i”次。

ie total * total+total * (total-1)+total * (total-2)....total * 1 即合计*合计+合计*(合计1)+合计*(合计2)....合计* 1

= total*(total+total-1+total-2...1) =总数*(总数+总数-1+总数-2 ... 1)

= total*(1+2+3....total) =总计*(1 + 2 + 3 ....总计)

= total*(sum of first 'total' natural numbers) =总数*(第一个“总数”自然数之和)

= total*(total*(total+1)/2) =总数*(总数*(总数+1)/ 2)

now the innermost loop also runs 'total-j' times for each middle loop 现在,最里面的循环也为每个中间循环运行“ total-j”次

ie total*(total*(total+1)/2)*(total+(total-1)+(total-2)....+1) 即合计*(合计*(合计+1)/ 2)*(合计+(合计-1)+(合计2).... + 1)

= total*(total*(total+1)/2)*(1+2+3....+total) =总数*(总数*(总数+1)/ 2)*(1 + 2 + 3 .... +总数)

= total*(total*(total+1)/2)* (sum of first 'total' natural numbers) =总数*(总数*(总数+1)/ 2)*(第一个“总数”自然数之和)

= total*(total*(total+1)/2) * (total*(total+1)/2).. So finally you will get something close to = total *(total *(total + 1)/ 2)*(total *(total + 1)/ 2)。因此,最终您会得到接近

total * (total*(total+1)/2) * (total*(total+1)/2). 总数*(总数*(总数+1)/ 2)*(总数*(总数+1)/ 2)。

Sorry there's a correction as @andreas mentioned innermost and middle loops run only till total-i-1 times in which case it will be the sum of first (total-1) no.s which should be (total-1)*total/2 so the final output should be 抱歉,有一个更正,因为@andreas提到最里面和中间的循环仅运行到total-i-1次,在这种情况下,这将是第一个(total-1)个数之和,应为(total-1)* total / 2,因此最终输出应为

total * (total*(total-1)/2) * (total*(total-1)/2) . 合计*(total *(total-1)/ 2)*(total *(total-1)/ 2)。

The equation is like below and the k is equal to total : 该方程如下所示,并且k等于total:

在此处输入图片说明

As we know, the sum of an arithmetic progression is: 众所周知,算术级数的总和为:

在此处输入图片说明

The inner-most loop will loop for 最内层的循环将循环

在此处输入图片说明

times, which is a function to j . 次,这是j的函数。

You sum it up and get a function to i , aka: 您对其进行归纳并得到i的函数,又称:

在此处输入图片说明

You sum it up again and get a function to total , aka: 您再次对其求和,得到一个totaltotal的函数:

在此处输入图片说明


For Mathematica users, the result is: 对于Mathematica用户,结果是:

f[x_]:=Sum[Sum[x-j,{j,i+1,x-1}],{i,0,x-1}]

From here , we can see it more clearly, and the FINAL result is: 这里 ,我们可以更清楚地看到它,并且最终结果是:

在此处输入图片说明

where x is total . 其中xtotal

If we run this loop 100 times and generate a data set, then graph it, we get this: 如果我们运行此循环100次并生成一个数据集,然后对其进行图形处理,则会得到以下结果: 在此处输入图片说明

Now, this graph is clearly a cubic. 现在,此图显然是立方的。 So we can do a solve using the cubic equation of ax^3+bx^2+cx+d. 因此我们可以使用ax ^ 3 + bx ^ 2 + cx + d的三次方程式进行求解。

Using 4 points, the values of them all are: 使用4点,它们的值均为:

在此处输入图片说明

So the full equation is 所以整个方程是

y=x^3/6-x/6
y=x(x^2/6-1/6)
y=(x/6)(x^2-1)

Interactive Graph: 互动图:

 <iframe src="https://www.desmos.com/calculator/61whd83djd?embed" width="500px" height="500px" style="border: 1px solid #ccc" frameborder=0></iframe> 

That function will loop (total/6)*(total*total - 1) times The snippet bellow just verifies that 该函数将循环(total/6)*(total*total - 1)次。

 var total = 100 var sum = 0; for(var i = 0; i < total; i++) { for(var j = i + 1; j < total; j++) { for(var k = j; k < total; k++) { sum++; } } } function calc(n) { return n*(n-1)*(n+1)/6 } console.log("sum: "+sum) console.log("calc: "+calc(total)) 

A simple loop like this: 像这样的简单循环:

for (i = a; i < b; i ++) {
    ....
}

runs ba iterations ( i takes the values: a , a+1 , a+2 ... b-2 , b-1 ) if a < b and 0 iterations otherwise. 如果a < b ,则运行ba次迭代( i取值: aa+1a+2 ... b-2b-1 ),否则运行0次迭代。 We will assume below that a < b always. 下面我们将始终假设a < b

Its number of iterations can be compute using the simple maths formula: 可以使用简单的数学公式计算其迭代次数:

总和(i = a,b-1)1

Applying the formula to your code 将公式应用于代码

We start with the innermost loop: 我们从最里面的循环开始:

for(int k = j; k < t; k++) {
    sum++;    
}

Its number of iterations is: 其迭代次数为:

总和(k = j,t-1)1

Using the formula above, the value of U is (t-1)-j+1 which means: 使用上面的公式, U值为(t-1)-j+1表示:

U = t - j

Adding the middle loop 添加中间循环

Adding the middle loop, the number of iterations becomes: 添加中间循环,迭代次数变为:

sum(j = i + 1,t)sum(k = j,t-1)1

The terms of the second sum are t-(i+1) , t-(i+2) , ... t-(t-2) , t-(t-1) . 第二和的项是t-(i+1)t-(i+2) ,... t-(t-2)t-(t-1)
By solving the parentheses and putting them in the reverse order they can be written as: 通过解决括号并将它们放在相反的顺序,它们可以写为:
1 , 2 , ... ti-2 , ti-1 . 12 ,... ti-2 ti-1

Let p = t - j . p = t - j The second sum now becomes: 现在第二个和为:

和(p = 1,t-i-1)p

It is the sum of the first ti-1 natural numbers and its value is: 它是第一个ti-1自然数总和,其值为:

sum(p = 1,t-i-1)p =(t-i-1)*(t-i)/ 2

Adding the outer loop 添加外循环

Adding the outer loop the sum becomes: 加上外循环,总和为:

sum(i = 0,t-1)sum(j = i + 1,t)sum(k = j,t-1)1 = sum(i = 0,t-1)((ti-1)*( ti)/ 2)= 1/2 * sum(i = 0,t-1)(((ti)-1)*(ti))

On the last sum, the expression (t - i) starts with t (when i = 0 ), continues with t-1 (when i = 1 ) and it keeps decreasing until it reaches 1 (when i = t - 1 ). 在最后一个总和上,表达式(t - i)t开头(当i = 0 ),以t-1开头(当i = 1 ),然后一直减小直到达到1 (当i = t - 1 )。 By replacing q = t - i , the last sum becomes: 通过替换q = t - i ,最后一个和成为:

1/2 * sum(q = 1,t)((q-1)* q)

The last expression subtracts the sum of the first n natural numbers from the sum of the first n square numbers . 最后一个表达式从前n平方数 的和中减去n自然数 的和 Its value is: 其值为:

S = 1/2 *(sum(q = 1,t)q ^ 2-sum(q = 1,t)q)= 1/2 *((t *(t + 1)*(2t + 1)) / 6-(t *(t + 1))/ 2)

Now it's easy to simplify the expression: 现在很容易简化表达式:

S = 1/2 * 1/6 *(t *(t + 1))*(2t + 1-3)= 1/6 *(t *(t + 1)*(t-1))=(t ^ 3-t)/ 6

The final answer 最终答案

The number of iterations of the posted code is: 发布的代码的迭代次数为:

(t ^ 3-t)/ 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM