0

对于任何给定的 N (>= 1),我如何计算这些循环将完成多少次迭代

for (1 <= k <= N)
    for (0 <= i < 6)
        for (0 <= j < k)
            ...

我特别有如何处理最内层循环的问题,因为它取决于最外层循环的值。基本上,它会像N * 6 * ???,但我不知道???应该是什么

4

2 回答 2

2

在不更改内部循环执行次数的情况下(尽管您将更改顺序),您可以将循环更改为:(可以这样做,i并且j彼此独立)

for (1 <= k <= N)
  for (0 <= j < k)
    for (0 <= i < 6)

暂时忽略i,我们有:

k             1  2    3     ... N
j             0  0 1  0 1 2     0 1 2 ... N-1
              -  ---  -----     -------------
executions    1   2     3             N

也就是说,1 + 2 + 3 + ... + N = N(N+1)/2执行(对于这些类型的计算,这是一个值得了解的众所周知的公式)。

添加i只是将其增加了 6 倍,所以我们有3*N(N+1).

于 2013-08-08T12:32:52.307 回答
1

???应该是 (N+1)/2,正整数的总和,不超过 N。只是为了确保我编写了一个 powershell 脚本来检查该理论:

for($N=1; $N -le 10; $N++)
{
  $totalCount = 0

  for ($k=1; $k -le $N; $k++)
  {
    for ($i=0; $i -lt 6; $i++)
    {
      for ($j=0; $j -lt $k; $j++)
      {    
        $totalCount++
      }
    }
  }

  Write-Host("Total Count for N={0} is {1}" -f $N, $totalCount)
  $calcTotal = ($N*($N+1)/2)*6
  Write-Host("Calulated total ={0}" -f $calcTotal)
}

产生:

Total Count for N=1 is 6
Calulated total =6
Total Count for N=2 is 18
Calulated total =18
Total Count for N=3 is 36
Calulated total =36
Total Count for N=4 is 60
Calulated total =60
Total Count for N=5 is 90
Calulated total =90
Total Count for N=6 is 126
Calulated total =126
Total Count for N=7 is 168
Calulated total =168
Total Count for N=8 is 216
Calulated total =216
Total Count for N=9 is 270
Calulated total =270
Total Count for N=10 is 330
Calulated total =330
于 2013-08-08T13:03:32.000 回答