How to find the smallest number with just 0 and 1 which is divided by a given number?

后端 未结 11 1335
情话喂你
情话喂你 2020-11-29 22:44

Every positive integer divide some number whose representation (base 10) contains only zeroes and ones.

One can prove that:

Consider the numbers 1, 11, 111,

11条回答
  •  情深已故
    2020-11-29 23:28

    There's an O(n)-time (arithmetic operations mod n, really) solution, which is more efficient than the answer currently accepted. The idea is to construct a graph on vertices 0..n-1 where vertex i has connections to (i*10)%n and (i*10+1)%n, then use breadth-first search to find the lexicographically least path from 1 to 0.

    def smallest(n):
        parents = {}
        queue = [(1 % n, 1, None)]
        i = 0
        while i < len(queue):
            residue, digit, parent = queue[i]
            i += 1
            if residue in parents:
                continue
            if residue == 0:
                answer = []
                while True:
                    answer.append(str(digit))
                    if parent is None:
                        answer.reverse()
                        return ''.join(answer)
                    digit, parent = parents[parent]
            parents[residue] = (digit, parent)
            for digit in (0, 1):
                queue.append(((residue * 10 + digit) % n, digit, residue))
        return None
    

提交回复
热议问题