Generalizing O(log log n) time complexity

为君一笑 提交于 2020-01-06 08:05:24

问题


I want to generalise how we get O(log log n)` time complexity. Yesterday I asked this question, in which I came to know, this:

for(i=1 ; i<n ; i*=2) { ... }

leads to O(log n) time complexity. By multiplying by 2 in each iteration, we are essentially taking next power of 2:

For O(log n)
   i=i*2
============
  1*2 = 2^1 = 2
  2*2 = 2^2 = 4
  4*2 = 2^3 = 8
 and so on

So to get O(log log n) time complexity, I need to take next double power (I coined this term "double power" for sake of convenience), something like this:

For O(log log n)
   i=i*2
================
 2^(2^1) = 4
 2^(2^2) = 16
 2^(2^3) = 256
 and so on

I guess this can be achieved with following loop (correct me if am wrong):

for(i=1,j=0; i<=n; i=2^(2^j)) { ... }

If we dont have to use power function in code and imitate same with multiplication, then we can do squaring to achieve the same time complexity:

For O(log log n)
   i=i*i
================
 2*2 = 2^(2^1) = 4
 4*4 = 2^(2^2) = (2^2)^2 = 4^2 = 16
 16*16 = 2^(2^3) = ((2^2)^2)^2 = 16^2 = 256
 and so on

This can be imitated by following loop:

for(i=2; i<=n; i*=i) { ... }

(Let me know if we can achieve O(log log n) time complexity by some other way in which loop control variable is multiplied not raised to some power.)

My main doubt is how we can generalize this?

(Till now all logs were with base 2, which from now onward, I will explicitly state as log_2)

I feel squaring loop counter in each iteration gave us O(log_2 log_2 n). So taking kth power of loop counter in each iteration will give us O(log_k log_k n).

For example, below loop will give us O(log_3 log_3 n):

for(i=3; i<=n; i*=i*i) { ... }

I tried to verify this by preparing table as follows:

For O(log log n)
   i*=i*i
================
 3*3*3 = 3^(3^1) = 27
 27*27*27 = 3^(3^2) = (3^3)^3 = 27^3 = 19683
            3^(3^3) = ((3^3)^3)^3 = 19683^3
 and so on

So am I correct with the quoted / highlighted fact?

来源:https://stackoverflow.com/questions/59590182/generalizing-olog-log-n-time-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!