Leetcode problem: Given a positive integer $K$, you need find the smallest positive integer $N$ such that $N$ is divisible by $K$, and $N$ only contains the digit $1$.
Return the length of $N$. If there is no such $N$, return $-1$.
Why does this following algorithm work here?
I'm asking here because although this was presented as a programming problem, it is at its core a math problem.
https://leetcode.com/problems/smallest-integer-divisible-by-k/
def smallestRepunitDivByK(K):
if K % 2 == 0 or K % 5 == 0:
return -1
N = 1
cnt = 1
while N % K > 0:
N = (N % K) * 10 + 1
cnt += 1
return cnt
Partial answer: I put together the demonstration below to motivate the mathematics to follow. But I don't have time to pursue the rest right now, so I'm putting this much out because I think it is instructive. If someone wants to invert the logic to derive the algorithm, feel free. If not, I'll do that later.
Let's follow it for $K = 7$
$$\begin{array}{c|c|c|c} \text{Cnt} & N & N \% K & 10(N\% K) + 1\\\hline 1&1&1&11\\2&11&4&41\\3&41&6&61\\4&61&5&51\\5&51&2&21\\6&21&0&-\end{array}$$
So the claim is $111111$ is divisible by $7$. Let's try to prove that in steps. In each step, I'll subtract the largest multiple of $7$ less than the left two digits:
$$\begin{align}111111&- 700000 = 41111\\41111&-350000 = 6111\\6111&-56000 = 511\\511& - 490 = 21\\21& - 21 = 0\end{align}$$
What jumps out here is that the values of $N$ in the algorithm are the first two digits of the remainders in this validation.