Hints for SRM 610, D2, 250-pointer (DivideByZero)

James S. Plank

Wed Feb 26 13:55:13 EST 2014
Problem Statement.
This one tripped up many of the Topcoder contestants -- in fact, only 68 percent of the contenstants got it. See if you can do better!
The constraints of this problem state that numbers only holds numbers between 1 and 100. Since (a div b) is always going to be less than a, John's paper will only hold numbers between 1 and 100. That puts some constraints on input that we can leverage. In particular, an n2 solution is going to be plenty fast enough, because the maximum n is 100.

Here's a solution that comes to mind -- keep two collections of numbers: those that you have processed (call it P -- it will be a vector), and those that you have not processed (call it N -- also a vector). You can also keep a table T of numbers on John's paper. T should be a vector with 101 elements, and T[i] is set to 1 if i is a number on John's paper. It is set to zero otherwise.

Do the following:

Let's illustrate this with Example 0, where numbers is { 9, 2 }. Below is the initial state of the three vectors (we only show the first 12 elements of T, because all of the higher ones will always be zero):

Now, run through N with an integer i. When i = 0, n = 9. We want to run through P, but P is empty, so we're done with n -- we add it to P:

Next, i = 1 and n = 2. We run through P and there is one element: p = 9. Since p is bigger than n, we set k = (p div n) = 4. We check to see if T[4] = 0, which it does, so we set T[4] = 1 and add 4 to N:

At this point, we're done with P, so we add n to P:

Finally, we continue with i = 2 and n = 4. We run through P: When p = 9, k = 2, and since T[2] equals 1, we ignore k. Similarly, when p = 2, k also equals 2, and since T[2] equals 1, we ignore k again. At this point, we're done with P, so we add n to P:

Now, we're done with N, so we return the size of P, which is three. As you can see, when we're done, P and N will be identical, so we could simply return the size of N.

I want you to think about why T is the way it is, and why it isn't, say, a vector containing the numbers on the paper. The reason is speed -- by having T be a vector of 101 elements, you can look up a number and see whether it is in T in one operation. That's much faster, than, say, looping through a vector to see if a number is there.