【问题标题】:Identify number of iterations of while loop确定while循环的迭代次数
【发布时间】:2016-04-17 20:10:45
【问题描述】:

我的计算机科学课上有这段代码:

int input=15;
while (input < n ) { input = input *3;}

这段代码有 log3(n/15) 循环的上限。我们怎样才能得到这个结果?

【问题讨论】:

  • 可以使用 Math 类的 log 方法
  • 你的算法是O(log n)。您的实际问题是什么?
  • 您不清楚哪一点?输入从 15 开始,每次增长 3 倍。

标签: java algorithm loops iteration time-complexity


【解决方案1】:

我认为他在谈论复杂性的分析解决方案。我认为是这样的(很久以前我做过对数):

15 * 3^x = n   // x would be the number of iterations until value reaches n

ln(15*(3^x)) = ln(n)
ln(15) + ln(3^x) = ln(n)
ln(15) + x*ln(3) = ln(n)
x = (ln(n) - ln(15)) / ln(3)
x = ln(n/15) / ln(3)
x = log3(n/15) / log3(3)
x = log3(n/15)

【讨论】:

    【解决方案2】:

    对于 n 的什么值,代码循环 k 次?

    必须是 15 = n(否则代码至少会再循环一次)。

    即3^k >= n/15 > 3^(k-1),取对数(以3为底),k >= log3(n/15) > k-1。

    因此 k 是大于或等于 log3(n/15) 的最小整数,或者根据需要等效地:k = ceil(log3(n/15))。

    【讨论】: