- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Smallest Integer Divisible by K in Python
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
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
Advertisements