Smallest Integer Divisible by K - Problem
Given a positive integer k, you need to find the length of the smallest positive integer n such that:
nis divisible byknonly 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, so we work with remainders using modular arithmetic.
Examples of numbers containing only 1s: 1, 11, 111, 1111, 11111...
Input & Output
example_1.py โ Basic Case
$
Input:
k = 1
โบ
Output:
1
๐ก Note:
The smallest integer containing only 1s that is divisible by 1 is just '1' itself, which has length 1.
example_2.py โ Small Prime
$
Input:
k = 3
โบ
Output:
3
๐ก Note:
We check: 1%3=1, 11%3=2, 111%3=0. So '111' is the first number containing only 1s divisible by 3, with length 3.
example_3.py โ Impossible Case
$
Input:
k = 2
โบ
Output:
-1
๐ก Note:
Any number containing only 1s is odd, so it can never be divisible by 2. Return -1.
Constraints
- 1 โค k โค 105
- k is a positive integer
- Time limit: Solution must run within reasonable time for all valid inputs
Visualization
Tap to expand
Understanding the Visualization
1
Check Feasibility
If k divisible by 2 or 5, impossible (repunits are always odd and never end in 0/5)
2
Build Remainders
Instead of huge numbers, track remainder = (remainder * 10 + 1) % k
3
Detect Success
When remainder becomes 0, we found our answer
4
Detect Cycles
If we see same remainder twice, no solution exists
Key Takeaway
๐ฏ Key Insight: Use modular arithmetic to track remainders instead of building massive numbers, and detect cycles to determine when no solution exists.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code