Smallest Integer Divisible by K Problem
Description
LeetCode Problem 1015.
Given a positive integer k, you need to find the length of 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.
Note: n may not fit in a 64-bit signed integer.
Example 1:
Input: k = 1
Output: 1
Explanation: The smallest answer is n = 1, which has length 1.
Example 2:
Input: k = 2
Output: -1
Explanation: There is no such positive integer n divisible by 2.
Example 3:
Input: k = 3
Output: 3
Explanation: The smallest answer is n = 111, which has length 3.
Constraints:
1 <= k <= 10^5
Solution
Approach: Follow the Remainders
The numbers made of 1s are 1, 11, 111, ..., each one 10 * previous + 1. They quickly overflow any integer type, but we only need to know when one is divisible by k, and remainders follow the same rule:
(10 * m + 1) % k = (10 * (m % k) + 1) % k
So we keep only r, the remainder of the current number, start with r = 1 % k (the % k matters for k = 1), and step r = (10 * r + 1) % k. The first length at which r is 0 is the answer.
When do we give up? There are only k possible remainders, and each step depends only on the current remainder. So within k steps either we reach 0, or some remainder comes back and from then on the same values repeat forever without reaching 0. That means after k steps without a 0, the answer is -1. (This happens exactly when k is divisible by 2 or 5, since a number ending in 1 is never a multiple of 2 or 5.)
Complexity: O(k) time and O(1) extra space.
class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
r = 1 % k # remainder of the repunit with `length` ones, divided by k
for length in range(1, k + 1):
if r == 0:
return length
r = (r * 10 + 1) % k
# k remainders were seen without a 0, so they repeat in a cycle that never reaches 0.
return -1