【问题标题】:Can some explain how many times is the print statement being executed有人能解释一下打印语句被执行了多少次吗
【发布时间】: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


【解决方案1】:

循环在第一次迭代中运行 2n 次,然后每次减少 1 次,直到第 (n+1) 次迭代运行n 次。

2n + (2n-1) + (2n-2) + … + n

请注意,本系列中有n+1 术语。

让我们从每个术语中减去n 并分别添加它们。这给了我们(n+1)*n 加上每个术语减去 n:

(n+1)*n + (2n-n) + (2n-1-n) + … + (n-n)

这简化为:

(n+1)*n + n + (n-1) + (n-2) + … + 0

现在,1+2+3+...+n(n+1)*n/2well known,而这正是 n + (n-1) + (n-2) + … + 0 的含义:

(n+1)*n + (n+1)*n/2

现在我们可以把它相乘了:

n^2 + n + (n^2)/2 + n/2

简化为:

1.5n^2 + 1.5n

【讨论】:

    【解决方案2】:

    所以让我们一步一步来。假设 n 的值为 4。

    i0 开始,所以 j 这次也从 0 开始
    j 递增直到比 2*n 小 1,即 8
    这意味着这次j的值将是0, 1, 2, 3, 4, 5, 6, 7,一共有8个不同的值

    i 递增到 1 所以 j 这次从 1 开始
    j 仍将递增直到比 2*n 小 1 或 8
    这次j的值将是1, 2, 3, 4, 5, 6, 7,一共有7个不同的值。比上次少1!

    下一次,j 的值将是 2, 3, 4, 5, 6, 7。 6个不同的值。

    这种模式将一直持续到j4 开始。然后j 将采用 4 个不同的值,循环将退出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2019-10-24
      • 1970-01-01
      • 2017-12-26
      相关资源
      最近更新 更多