views:

91

answers:

1

Do the two algorithms have the same theta characterization of Θ(n^2)?

int sum = 0;
for (int i = 0; i < n; i++ )
    for (int j = 0; j < n * n; j++ )
        sum++;

int sum = 0;
for ( int i = 0; i < n; i++)
    for ( int j = 0; j < i; j++)
        sum++;

If not then does this mean that this characterization is not Θ(n^3)?

int sum = 0;
for ( int i = 0; i < n; i++)
    for ( int j = 0; j < i * i; j++ )
        for ( int k = 0; k < j; k++ )
            sum++;
+2  A: 

@Dan, For the first one did you really mean j < n * n rather than j < n? If so, the time complexity of the first one is Θ(n^3), isn't it?

If you meant j < n, then I believe the first two are both Θ(n^2): The first one takes n^2 steps, and the second one takes 1 + 2 + ... + n = n(n+1)/2 which is Θ(n^2).

I'm thinking the 3rd one is Θ(n^4), but it's harder to prove. Definitely O(n^4).

LarsH
@LarsH yes i did mean j<n*n. the first 2 are the same algorithms besides the inner loop comparison. I knew that the second one was Θ(n^2) but not when there was a multiplcation involved such as the first and third algorithm. So does this mean that the multiplication increases the degree by 1?
Dan
@Dan The multiplication increases the degree by n, not 1. `for(int i=0;i<n*n;i++)` loops n^2 times. @larsH Θ(n^4) indeed.
Tony Ennis
@Tony when @Dan said degree I believe he was talking about the exponent. So yes @Dan if you multiply n^k * n, you get n^(k+1). I'm not sure if that's what you're asking though.
LarsH