I came across this question in an interview.
Any number with 3 in its units position has at least one multiple containing all ones. For instance, a multiple of 3 is 111, a multiple of 13 is 111111. Given a number ending in 3, I was asked the best method to find its multiple containing all 1’s.
Now a straightforward approach is possible, where you do not consider space issues but as the number grows, and sometimes even if it doesn’t, an int (or a long int at that!) in C cannot hold that multiple.
What is the optimal way to implement such an algorithm in C?
I came across this question in an interview. Any number with 3 in its
Share
UPDATE: Incorporating Ante’s observations and making the answer community wiki.
As usual in this type of problems, coding any working brute-force algorithm is relatively easy, but the more math. you do with pencil and paper, the better (faster) algorithm you can get.
Let’s use a shorthand notation: let M(i) mean 1111…1 (i ones).
Given a number n (let’s say n = 23), you want to find a number m such that M(m) is divisible by n. A straightforward approach is to check 1, 11, 111, 1111, … until we find a number divisible by n. Note: there might exist a closed-form solution for finding m given n, so this approach is not necessarily optimal.
When iterating over M(1), M(2), M(3), …, the interesting part is, obviously, how to check whether a given number is divisible by n. You could implement long division, but arbitrary-precision arithmetic is slow. Instead, consider the following:
Assume that you already know, from previous iterations, the value of
M(i) mod n. IfM(i) mod n = 0, then you’re done (M(i)is the answer), so let’s assume it’s not. You want to findM(i+1) mod n. SinceM(i+1) = 10 * M(i) + 1, you can easily calculateM(i+1) mod n, as it’s(10 * (M(i) mod n) + 1) mod n. This can be calculated using fixed-precision arithmetic even for large values of n.Here’s a function which calculates the smallest number of ones which are divisible by n (translated to C from Ante’s Python answer):