Computing costs

Is there anyone who knows what the computational cost is for these two pieces of code?

while (n > 2)
   n = sqrt(n);

while (n > 2)
   n = log(n);
+2
source share
2 answers

The second will be O(log* n)where log *is the iterated logarithm .

Analysis of the first gives the following:

sqrt(n) = n ^ (1/2)
sqrt(sqrt(n)) = n ^ (1/4)
sqrt(sqrt(sqrt(n))) = n ^ (1/8)
...
sqrt applied k times = n ^ (1/2^k)

Keep in mind that the first algorithm executes ktimes (basically, the number of times that we must apply sqrtbefore n <= 2).

Consider this reasoning:

n ^ (1/2^k) = p (p <= 2) | ^ (2^k)
n = p ^ (2^k) | log
log n = (2^k) log p | log
log log n = log (2 ^ k) + log log p
log log n = klog2 + log log p
=> k ~= log log n

So, the first algorithm O(log log n).

+9
source

The answer to the first should be obvious if he redid it in the journal domain:

n = log2(n);
while (n > 1)
    n = n / 2;

How many times do you need to halve the number to reach 1? O (log n).

+4

Source: https://habr.com/ru/post/1751970/


All Articles