Time complexity 嵌套依赖循环的理论时间复杂度计算
如何计算具有相关索引的以下嵌套for循环的大O时间复杂度:Time complexity 嵌套依赖循环的理论时间复杂度计算,time-complexity,language-agnostic,big-o,nested-loops,complexity-theory,Time Complexity,Language Agnostic,Big O,Nested Loops,Complexity Theory,如何计算具有相关索引的以下嵌套for循环的大O时间复杂度: void function1 (int n) { int x = 0; for (int i = 0; i <= n/2; i+=3) for (int j = i; j <= n/4; j+=2) x++; } void函数1(int n) { int x=0; for(int i=0;i代码的复杂度定义为给定的n执行代码的次数 有两种方法可以做到这一点。 模拟:
void function1 (int n)
{
int x = 0;
for (int i = 0; i <= n/2; i+=3)
for (int j = i; j <= n/4; j+=2)
x++;
}
void函数1(int n)
{
int x=0;
for(int i=0;i代码的复杂度定义为给定的n
执行代码的次数
有两种方法可以做到这一点。
模拟:针对不同的n
值运行代码并找出值。在这种情况下,这相当于x
的最终值
理论上:
让我们首先检查每个i
代码的运行次数:
使用算术级数公式(a_n=a_1+(k-1)*d):
i=0
=>n/4=0+(k-1)*2次
i=3
=>n/4=3+(k-1)*2次
i=6
=>n/4=6+(k-1)*2次
i=9
=>n/4=9+(k-1)*2次
现在让我们检查一下最后一个我的
:
i=n/4
=>n/4=n/4+(k-1)*2次
i=n/4-3
=>n/4=(n/4-3)+(k-1)*2
=>3/2+1
次
i=n/4-6
=>n/4=(n/4-6)+(k-1)*2
=>6/2+1
次
因此,内部循环将运行的总次数为:
= (1) + (3/2 + 1) + (6/2 + 1) + (9/2 + 1) ... + ((n-12)/8 + 1)+ (n/8 + 1)
=> (0/2 + 1) + (3/2 + 1) + (6/2 + 1) + (9/2 + 1) ... + ((n-12)/8 + 1)+ (n/8 + 1)
可以写为:
=> (0/2 + 3/2 + 6/2 + ... (n-12)/8 + n/8) + (1 + 1 + 1 ... 1 + 1)
让我们假设序列中有总的p项:
让我们看看P:
n/8 = (0/2) + (P-1)*(3/2) => P = (n+12)/12
现在总结上述系列:
= [(P/2) (0/2 + (P-1) * 3/2)] + [P]
= P(3P+1)/4
= (n+12)(3(n+12)+12)/(4*12*12)
= (n^2 + 28n + 96)/192
因此,代码的最终复杂性是
= (number of operation in each iteration) * (n^2 + 28n + 96)/192
现在看看术语(n^2+28n+96)/192
,对于一个非常大的n
,这将接近~n^2
以下是复杂性比较:
线性尺度很难分析到我绘制的对数尺度。虽然对于小的n
你看不到复杂性收敛到n^2
使用非常放松的方法,可以说:
for (int i = 0; i <= n/2; i+=3){
for (int j = i; j <= n/4; j+=2) {
x++;
}
}
可以使用公式(b-a)/c
计算。因此,内部循环将运行大约((n/4)-i)/2)
次或n/8-i/2次
外部循环可以被认为是从k=0运行到n/12
the summation of [k=0 to n/12] of (n/8 - 3k/2),
这相当于
the summation [k=0 to n/12] of n/8 - the summation [k=0 to n/12] of 3k/2.
因此,
(N^2)/96-3k/2的总和[[k=0到N/12]
这大约是(n^2)/192
。因此,上限是O(n^2)
for (int j = a; j < b; j += c)
the summation of [k=0 to n/12] of (n/8 - 3k/2),
the summation [k=0 to n/12] of n/8 - the summation [k=0 to n/12] of 3k/2.