views:

173

answers:

3
for i := 1 to n do
  j := 2;
  while j < i do
    j := j^4;

I'm really confused when it comes to Big-O notation, so I'd like to know if it's O(n log n). That's my gut, but I can't prove it. I know the while loop is probably faster than log n, but I don't know by how much!

Edit: the caret denotes exponent.

A: 

Looks like it is O(i log4 j) -- but it has been a while.

(log4 means log base 4)

Hogan
Yeah, it looks like that to me, too. But if j is increasing, then the base changes, right? It would be log 4 if j started out at 4 and it was being multiplied by 4 at each iteration of the while loop, I think....
swiftee
@Hogan Huh? Where did the i factor come from?
LarsH
@Hogan This is just fundamentally wrong. Big-O bounds are given in terms of the problem size; the iterators used to traverse the problem are meaningless in the bound.
Tyler McHenry
@Tyler I know it's wrong, but I figured he meant O(nlogn) cuuz...they might have been typos?
swiftee
@Tyler Did you vote up Maciej's answer? I'm interested to know because you were/are a theory guy.
swiftee
Yes, I believe Maciej's answer is correct.
Tyler McHenry
@LarsH, @Tyler : yeah I miss read the problem -- n is the problem size.
Hogan
+2  A: 

Off the cuff, I'd guess is it is O(n slog4 n) where slog represents the inverse of the tetration operator. Tetration is the next operation after exponentiation. Just like multiplication is iterated addition, and exponentiation is iterated multiplication, tetration is iterated exponentiation.

My reasoning is, if you multiplied j by 4 each iteration then the function would be O(n log4 n). But since you are exponentiating it each iteration, you need a correspondingly more powerful operator than log: slog.

John Kugelman
+1 I'm not sure you're right, but it's resourceful reasoning. :-)
LarsH
Hm, yeah, thinking about it more this doesn't seem right. But I'll leave the answer up for the educational value! Heh.
John Kugelman
@John, lol, I was thinking that it was (essentially) that operator, too! It's not the answer, but now I know what it's called! (Googling "log of a log of a log" didn't give me much luck. haha
swiftee
+13  A: 

The problem is the number of iterations the while loop is executed for a given i.

On every iteration j:= j^4 and at the beginning j := 2, so after x iterations j = 24^x

j < i is equivalent to x < log_4(log_2(i))

I'd risk a statement, that the complexity is O(n * log_4(log_2(n)))

You can get rid of constant factors in Big O notation. log_4(x) = log(x) / log(4) and log(4) is a constant. Similarly you can change log_2(x) to log(x). The complexity can be expressed as O(n*log(log(n)))

Maciej Hehl
+1 I believe this is right. And since big-O notation ignores multiplication by a constant M, this is equivalent to O(n log(log(n)). So the OP is right, the while loop is faster than log(n).
LarsH