Smallest Integer Divisible by K in Python

PythonServer Side ProgrammingProgramming

Suppose we have a positive integer K, we need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. We have to find the length of N. If there is no such N, return -1. So if the input is like 3, then the output will be 3. The smallest answer will be N = 111.

To solve this, we will follow these steps −

  • if k is even, or k is divisible by 5, then return -1
  • set r := 0 and N = 1
  • for i in range 1 to K + 1
    • r := (r * 10 + 1) mod k
    • if r = 0, then return i

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Input

11

Output

2
raja
Published on 30-Apr-2020 07:50:45
Advertisements