Smallest Integer Divisible by K in Python

Given a positive integer K, we need to find the smallest positive integer N such that N is divisible by K and N contains only the digit 1 (like 1, 11, 111, 1111, etc.). We return the length of such number N, or -1 if no such number exists.

For example, if K = 3, the smallest number containing only 1s that is divisible by 3 is 111, so we return 3 (the length).

Algorithm

To solve this problem, we follow these steps:

  • If K is even or divisible by 5, return -1 (no solution exists)
  • Initialize remainder r = 0
  • For i from 1 to K:
    • Update r = (r × 10 + 1) mod K
    • If r becomes 0, return i (length found)

Why Even Numbers and Multiples of 5 Return -1

Numbers containing only 1s are always odd, so they can never be divisible by even numbers. Similarly, numbers ending only in 1 can never be divisible by 5 (since multiples of 5 must end in 0 or 5).

Example

class Solution:
    def smallestRepunitDivByK(self, K):
        if K % 2 == 0 or K % 5 == 0:
            return -1
        
        r = 0
        for i in range(1, K + 1):
            r = (r * 10 + 1) % K
            if r == 0:
                return i
        
        return -1

# Test the solution
solution = Solution()
print(f"K = 3: {solution.smallestRepunitDivByK(3)}")
print(f"K = 7: {solution.smallestRepunitDivByK(7)}")
print(f"K = 11: {solution.smallestRepunitDivByK(11)}")
print(f"K = 6: {solution.smallestRepunitDivByK(6)}")

The output of the above code is:

K = 3: 3
K = 7: 6
K = 11: 2
K = 6: -1

How It Works

The algorithm uses modular arithmetic to efficiently check divisibility. Instead of constructing large numbers like 111111, we track only the remainder when dividing by K:

  • For N = 1: remainder = 1 % K
  • For N = 11: remainder = (1×10 + 1) % K
  • For N = 111: remainder = ((1×10 + 1)×10 + 1) % K

Step-by-Step Example

Let's trace through K = 3:

K = 3
r = 0

# i = 1: Check if 1 is divisible by 3
r = (0 * 10 + 1) % 3 = 1  # Not zero

# i = 2: Check if 11 is divisible by 3  
r = (1 * 10 + 1) % 3 = 2  # Not zero

# i = 3: Check if 111 is divisible by 3
r = (2 * 10 + 1) % 3 = 0  # Zero! Return 3

print("111 ÷ 3 =", 111 // 3)  # Verify: 111 ÷ 3 = 37

The output of the above code is:

111 ÷ 3 = 37

Conclusion

This algorithm efficiently finds the smallest repunit (number with only 1s) divisible by K using modular arithmetic. It returns -1 for even numbers and multiples of 5, since no such repunit exists for these cases.

Updated on: 2026-03-25T08:31:24+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements