Algorithm in C - playing with numbers - number with 3 in units place

后端 未结 4 719
闹比i
闹比i 2020-12-24 08:46

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

4条回答
  •  北海茫月
    2020-12-24 09:37

    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. If M(i) mod n = 0, then you're done (M(i) is the answer), so let's assume it's not. You want to find M(i+1) mod n. Since M(i+1) = 10 * M(i) + 1, you can easily calculate M(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):

    int ones(int n) {
            int i, m = 1;
            /* Loop invariant: m = M(i) mod n, assuming n > 1 */
            for (i = 1; i <= n; i++) {
                    if (m == 0)
                            return i;  /* Solution found */
                    m = (10*m + 1) % n;
            }
            return -1;  /* No solution */
    }
    

提交回复
热议问题