Problem 853
Smallest Integer Divisible by K
Medium · 20 pts · Math, Hash Table
Problem
Find the length of the smallest positive integer made only of the digit 1 (like 1, 11, 111, ...) that is divisible by K, or print -1 if no such number exists. The numbers get huge, so keep only the remainder: r = (r × 10 + 1) mod K. If K is divisible by 2 or 5 the answer is -1; otherwise the remainders must reach 0 within K steps, by the pigeonhole principle.
Input
A single integer K.
Output
Print the length of the smallest repunit divisible by K, or -1.
Constraints
1 <= K <= 10^5
Example input
3
Example output
3
Explanation
For K = 3, the number 1 leaves remainder 1 and 11 leaves remainder 2, but 111 = 3 × 37. So the answer is 3.