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:

  • n is divisible by k
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: k = 1
Output: 1
💡 Note: The smallest integer containing only 1's that is divisible by 1 is "1" itself, which has length 1.
Example 2 — Requires Multiple 1's
$ Input: k = 3
Output: 3
💡 Note: We need to find the smallest number with only 1's divisible by 3: 1%3=1, 11%3=2, 111%3=0. So "111" with length 3 is the answer.
Example 3 — Impossible Case
$ Input: k = 2
Output: -1
💡 Note: Numbers containing only 1's are always odd, so they can never be divisible by 2. Return -1.

Constraints

  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Smallest Integer Divisible by K Modular Arithmetic with Cycle Detection INPUT Given Value k = 1 Numbers to Check: 1 11 111 ... GOAL: Find smallest n with only 1s that is divisible by k k is a positive integer n can be very large! (May not fit in 64-bit int) ALGORITHM STEPS 1 Check Special Case If k % 2 == 0 or k % 5 == 0 return -1 (never works) 2 Initialize Remainder remainder = 0, length = 0 Track seen remainders 3 Iterate with Modular Math rem = (rem * 10 + 1) % k length++ 4 Check Conditions If rem == 0: return length If cycle found: return -1 Trace for k = 1: i=1: rem=(0*10+1)%1 = 0 rem == 0, so return 1 n = "1" is divisible by 1 FINAL RESULT Output 1 Explanation: The number "1" has length 1 and 1 % 1 = 0 (divisible!) VERIFIED 1 / 1 = 1 ... OK Complexity: Time: O(k) Space: O(1) (At most k unique remainders) Key Insight: Instead of building actual numbers (which overflow), we track only remainders using modular arithmetic. Building "111...1" iteratively: next_remainder = (prev_remainder * 10 + 1) % k. If remainder becomes 0, we found divisibility. By Pigeonhole Principle, if we see same remainder twice, cycle exists --> return -1. TutorialsPoint - Smallest Integer Divisible by K | Modular Arithmetic with Cycle Detection
Asked in
Google 15 Facebook 12
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen