10

I have a short program here:

Given any n:
i = 0;
while (i < n) {
   k = 2;
   while (k < n) {
        sum += a[j] * b[k]
        k = k * k;
   }
   i++;
}

The asymptotic running time of this is O(n log log n). Why is this the case? I get that the entire program will at least run n times. But I'm not sure how to find log log n. The inner loop is depending on k * k, so it's obviously going to be less than n. And it would just be n log n if it was k / 2 each time. But how would you figure out the answer to be log log n?

4

3 回答 3

8

对于数学证明,内循环可以写成:

T(n) = T(sqrt(n)) + 1

w.l.o.g assume 2 ^ 2 ^ (t-1)<= n <= 2 ^ (2 ^ t)=>
we know  2^2^t = 2^2^(t-1) * 2^2^(t-1)
T(2^2^t) = T(2^2^(t-1)) + 1=T(2^2^(t-2)) + 2 =....= T(2^2^0) + t =>
T(2^2^(t-1)) <= T(n) <= T(2^2^t) = T(2^2^0) + log log 2^2^t = O(1) + loglogn

==> O(1) + (loglogn) - 1 <= T(n) <= O(1) + loglog(n) => T(n) = Teta(loglogn).

然后总时间为 O(n loglogn)。

为什么内循环是 T(n)=T(sqrt(n)) +1? 首先看内循环何时中断,当k>n时,表示在k之前至少为sqrt(n),或者在最多为sqrt(n)之前的两级,所以运行时间为T(sqrt(n)) + 2 ≥ T(n) ≥ T(sqrt(n)) + 1。

于 2011-03-05T10:17:29.360 回答
0

我想如果代码是这样的,应该是 n*log n;

i = 0;
while (i < n) {
    k = 2;
    while (k < n) {
        sum += a[j] * b[k]
        k *= c;// c is a constant bigger than 1 and less than k;
    }
i++;
}
于 2019-09-19T13:20:23.787 回答
0

如果循环变量以恒定的量以指数方式减少/增加,则循环的时间复杂度为 O(log log n)。如果循环变量除以/乘以一个常数,则复杂度为 O(Logn)。

例如:在您的情况下, k 的值如下。让括号中的 i 表示循环已执行的次数。

 2 (0) , 2^2 (1), 2^4 (2), 2^8 (3), 2^16(4), 2^32 (5) , 2^ 64 (6) ...... till n (k) is reached. 
The value of k here will be O(log log n) which is the number of times the loop has executed.

为了假设,我们假设n2^64。现在log (2^64) = 64log 64 = log (2^6) = 6.因此你的程序运行6时间n是什么时候2^64

于 2017-06-17T09:57:23.460 回答