1

Can someone please explain to me how to calculate the complexity of the following recursive code:

long bigmod(long b, long p, long m) {
    if (p == 0)
        return 1;
    else
    if (p % 2 == 0)
        return square(bigmod(b, p / 2, m)) % m;
    else    
        return ((b % m) * bigmod(b, p - 1, m)) % m;
}

4 Answers 4

2

This is O(log(p)) because you are dividing by 2 every time or subtracting one then dividing by two, so the worst case would really take O(2 * log(p)) - one for the division and one for the subtraction of one.

Note that in this example the worst case and average case should be the same complexity.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to be more formal about it then you can write a recurrence relation and use the Master theorem to solve it. http://en.wikipedia.org/wiki/Master_theorem

Comments

0

It runs in O(log n)

There are no expensive operations (by that i more expensive than squaring or modding. no looping, etc) inside the function, so we can pretty much just count the function calls.

Best case is a power of two, we will need exactly log(n) calls.

Worst case we get an odd number on every other call. This can do no more than double our calls. Multiplication by a constant factor, no worse asymptotically. 2*f(x) is still O(f(x))

O(logn)

6 Comments

if the number is negative you subtract 1 from it , it becomes positive than divides by 2, so it cant be log(n) even in worse case.
i didnt follow that, can you try again? If which number is negative? I take our answers as saying pretty much the same thing, i dont see the difference
so p is either positive than we divide by 2, or negative than we subtract one and have to divide by two right after.
if p is even we divide by two. if p is odd we subtract by one. positive/negative?
ya the main idea of why it cant be O(n) is that you cant keep subtracting by 1 without going to a positive number. worse case is really negative take 1 way >> positive >> divide by 2 >> back to negative >> take another one away etc.
|
0

It is o(log(N)) base 2, because the division by 2

1 Comment

I think you should add an explanation why this is so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.