Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computational cost

Tags:

c++

c

algorithm

Is there someone that knows what the computational cost for this two pieces of code is?

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

while (n > 2)
   n = log(n);
like image 550
BlackShadow Avatar asked Aug 16 '26 04:08

BlackShadow


1 Answers

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

Analysing the first one yields something like this:

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)

Consider that the first algorithm executes k times (basically, the number of times we have to apply sqrt until 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 is O(log log n).

like image 50
IVlad Avatar answered Aug 18 '26 19:08

IVlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!