views:

438

answers:

2

Can anyone help with with the time complexity of this algorithm, and why it is O(n^2). A step by step explanation would be helpful, thanks!

function divide(x,y)
    Input: Two n-bit integers x and y, where y >= 1
    Output: The quotient and remainder of x divided by y

    if x = 0:
        return (q,r) = (0,0)

    (q,r) = divide(x/2, y)
    q = 2q
    r = 2r

    if x is odd:
        r = r + 1

    if r >= y:
        r = r - y
        q = q + 1

    return (q,r)
A: 

Due to the recursion, divide() is called up to n times.

Suppose simple arithmetic on n-bit integers takes O(n) time. (This is true in all the big integer implementations I know about -- in Python, for example, adding 1 to a big integer copies the whole thing.)

Then we have a finite number of O(n) operations happening up to n times. This takes O(n^n) time.

def divide(x, y):
    assert y >= 1
    if x == 0:
        return 0, 0
    q, r = divide(x // 2, y)
    q *= 2
    r *= 2
    if x & 1:
        r += 1
    if r >= y:
        r -= y
        q += 1
    return q, r
Jason Orendorff
I think you have your n's confused. Arithmetic on a single n-bit integer will be O(1), not O(n), since I believe the n being talked about is the value of x passed to the function. divide() is NEVER called up to n times. Passing in 1024 will result in divide only being called 10 times.
paxdiablo
But Pax, your post says that x and y are "Two n-bit integers".
Jason Orendorff
The N in O(N) is either the value of x or the number of bits n - it can't be both. I took the question to state that it was a single integer unit (int), not a general array of them (int[]) which make the bigO dependent on two input variables. Need clarification from questioner.
paxdiablo
(Correction, the original post is by keval, not Pax.)
Jason Orendorff
+1  A: 

The worst case, where every bit in x is 1 (e.g. 0xffff), is O(n). The trick is to convert the recursion into an iteration.

splicer
@splicer, I think the worst case is when the *top* bit is one, not necessarily all bits. But, now we've established that n is the number of bits, not the value of x, O(n) is the right answer, despite the question. +1 and deleting my answer that assumed n was value of x rather than bitcount.
paxdiablo
@Pax - Yes, you're correct: the worst case is when the MSB is set.
splicer