You can solve this with BFS starting at 0, where the neighboring vertices with number n are 10n + 2, 10n + 3, 10n + 5 and 10n + 7. By keeping a record of all mod p numbers already queued, you can reduce the size search space, but itβs more important to know when the entire space was searched.
Here is a simple Python implementation:
import collections def ns(n, p): q = collections.deque([0]) done = set() while q: x = q.popleft() for d in [2, 3, 5, 7]: nn = 10 * x + d if nn % p in done: continue if nn % p == n: return nn q.append(nn) done.add(nn % p) return -1 assert ns(52, 100) == 52 assert ns(11, 100) == -1 assert ns(51, 1123) == 322352 assert ns(0, 55) == 55
Paul hankin
source share