(Kind of) Daily algorithm practice: Big O in a division function
Here is today’s problem, VI.4:
Sorry, photo quality is kind of crap.
Anyway, I spent way too many days looking at this one, thinking "yeah, I have no idea, let's push this to tomorrow". But, today I decided to actually sit down and figure it out. And now that I understand it, it's not too bad!
We have a while loop here, so we're probably not going to have an O(1) algorithm or anything like that. In fact, if you don't look at it too closely, you might think "lmao yeah, that's O(a) because it goes until the sum is a" and you would be wrong.
Instead, we have to think about the purpose of this function. What is it doing, exactly? It's dividing two integers! a/b.
Remember that. a/b.
And what do we return? COUNT.
If you notice, count is incremented within every single iteration of the while loop. This while loop is our key to understanding the complexity here. The value of count represents the final complexity of our algorithm, because count is explicitly tied to the while loop. It loops some number of times X. This number X will be our final result.
Thus, since the while loop will iterate count times, and count will have a result of a/b by definition, this algorithm is O(a/b).
We can see an example of this by setting a = 50 and b = 5, for reference. If you do this by hand, you will get a final result of 10, which is 50/5 = a/b.
And thus it is.
Comments
Post a Comment