计算迭代量

时间:2013-08-08 12:23:15

标签: loops complexity-theory

如何计算任何给定N(> = 1)的这些循环将完成的迭代次数

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

我特别遇到如何处理最内层循环的问题,因为它取决于最外层循环的值。 Basicall,它会像N * 6 * ???,但我无法弄清???应该是什么

2 个答案:

答案 0 :(得分:2)

不改变内部循环的执行次数(尽管您将更改顺序),您可以将循环更改为:(这可以完成,因为ij独立于每个循环其它)

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次执行(a well-known formula值得了解这些类型的计算)。

添加i只会将此增加6倍,因此我们有3*N(N+1)

答案 1 :(得分: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