Problem Description
Given a positive integer k, find the length of the smallest positive integer n such that n is divisible by k and n consists only of the digit 1. If no such n exists, return -1.
Key Insights
- The number n is built solely from the digit '1', making it a repunit number.
- Direct construction of n is infeasible due to its potential size. Instead, use modulo arithmetic to only track remainders.
- Repeatedly update the remainder by computing (previous_remainder * 10 + 1) mod k.
- If the remainder becomes 0, the current length is the answer.
- If a remainder repeats (cycle detected), return -1 because no divisible repunit exists.
Space and Time Complexity
Time Complexity: O(k) - At most k iterations
Space Complexity: O(k) - In the worst-case storing up to k remainders
Solution
We use modulo arithmetic to avoid constructing large numbers. Starting with the remainder of 1 mod k, we iteratively update the remainder by appending the digit '1'. At each iteration, if the remainder is zero, we return the count of digits. We use a set to record seen remainders to detect cycles. This prevents infinite loops if no valid number exists. This technique efficiently determines the length of the smallest repunit divisible by k without handling enormously large integers.