【发布时间】:2018-10-18 00:45:00
【问题描述】:
// For the below algorithm, calculate the exact number of times
// System.out.println statement is executed as a function of n. Assume n≥1
for (int i=0; i<=n; i++) {
for (int j = i; j < 2*n; j++) {
System.out. println(”1 iteration executed!”);
}
}
这是解决方案,但我很难理解数学。
Overall RT = 2n + (2n-1) + (2n-2) + … + n =
= (n+1)*n + (n+(n-1)+(n-2)+…+1+0) =
= n2 + n + n*(n+1)/2 =
= 1.5*n2 + 1.5n
【问题讨论】:
-
更多的是数学问题而不是编程问题。
-
哪一部分你不明白?你明白为什么是
2n + (2n-1) + (2n-2) + … + n了吗? -
是不是因为内循环运行2n,外循环每次迭代后都运行(2n-1)。接下来的 3 行我不知道发生了什么。
标签: java algorithm performance