以Θ(·)表示法将运行时间计算为N的函数。
public static void p5(int N) {
for (int i = 1; i <= N * N; i *= 2) {
for (int j = 0; j < i; j++) {
System.out.println("moo");
}
}
}
为此,我开始为N的多个值计算运行时间。
N = 1 C(N)= 1,因为j =仅0
N = 2 C(N)= 7因为i = 1时j = 0,i = 2时j = 0.1,i = 4时j = 0,1,2,3
N = 3 C(N)= 15因为i = 1时j = 0,i = 2时j = 0.1,i = 4时j = 0,1,2,3 i = 8时j = 0,1,2,3,4,5,6,7
因此,有一种模式:
C(1)= 1 = 2 ^ 0
C(2)= 7 = 2 ^ 0 + 2 ^ 1 + 2 ^ 2
C(3)= 15 = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + 2 ^ 3
C(4)= 31 = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + 2 ^ 3 + 2 ^ 4
C(N)= 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + 2 ^ 3 + 2 ^ 4 +…+ 2 ^ N = 2 ^(N + 1)-1
所以,我得到Θ(2 ^ N)作为答案! 但是,答案是N ^ 2。
您能帮助我了解问题出在哪里吗?
答案 0 :(得分:1)
p5
的复杂度实际上是O(n^2)
,您可以正式计算它;或简单地编辑方法,使其返回执行的周期数;并计算比率ops/(N^2)
来证明这一点。下面的代码转储输出:
p5 N=1 took op=1 operations, ratio=1,000000
p5 N=2 took op=7 operations, ratio=1,750000
p5 N=4 took op=31 operations, ratio=1,937500
p5 N=8 took op=127 operations, ratio=1,984375
p5 N=16 took op=511 operations, ratio=1,996094
p5 N=32 took op=2047 operations, ratio=1,999023
#etc..
和代码:
package sample;
public class SampleComplexity {
public static int p5(int N) {
int res = 0;
for (int i = 1; i <= N * N; i *= 2) {
for (int j = 0; j < i; j++) {
//count operations here
res++;
}
}
return res;
}
public static void main(String[] args) {
int N=1;
for (int i=0;i<10;i++) {
int p5 = p5(N);
System.out.printf("p5 N=%d took op=%d operations, ratio=%f%n", N, p5, 1.*p5/N/N);
N=N*2;
}
}
}
答案 1 :(得分:0)
例如,您的错误在这里:
C(4)= 31 = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + 2 ^ 3 + 2 ^ 4
如果在Θ函数中输入4,则您有2⁴,这不等于您计算出的值。