简体   繁体   English

确定while循环的迭代次数

[英]Identify number of iterations of while loop

I have this code from my computer science class: 我的计算机科学课上有以下代码:

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

This code has the ceiling of log3(n/15) loops. 此代码的上限为log3(n / 15)个循环。 How can we obtain this result? 我们如何获得这个结果?

I think he is talking about the analytical solution to complexity. 我认为他正在谈论复杂性的解析解决方案。 I think it's something like this (long time ago i did logaritms): 我认为是这样的(很久以前我做了对数):

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)

For what values of n does the code loop k times? 代码将n的哪个值循环k次?

It must be that 15 < n, and 15*3 < n and 15*3*3 < n and .... and 15*3^(k-1) < n. 必须是15 <n,15 * 3 <n和15 * 3 * 3 <n以及....和15 * 3 ^(k-1)<n。 Also, it must be that 15*3^k >= n (otherwise the code would do at least one more loop). 同样,必须是15 * 3 ^ k> = n(否则代码将至少执行一个循环)。

That is, 3^k >= n/15 > 3^(k-1), and taking logs (base 3), k >= log3(n/15) > k-1. 即3 ^ k> = n / 15> 3 ^(k-1),取对数(以3为底),k> = log3(n / 15)> k-1。

Thus k is the smallest integer greater than or equal to log3(n/15), or equivalently: k = ceil(log3(n/15)) as required. 因此,k是大于或等于log3(n / 15)或等于的最小整数:k = ceil(log3(n / 15))根据需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM