Open In App

Python Program for Smallest K Digit Number Divisible by X

Last Updated : 14 Nov, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

Given two integers X and K, the task is to find the smallest K-digit number that is perfectly divisible by X. For example:

Input: X = 5, K = 2
Output: 10
Explanation: 10 is the smallest 2-digit number divisible by 5.

Let's explore different methods to solve this problem efficiently in Python.

Using math.ceil() Function

This method uses the math.ceil() function to compute the smallest multiple of X greater than or equal to 10 ^ (K-1) in a single step. It’s concise and efficient.

Python
import math
X, K = 83, 5
MIN = 10 ** (K - 1)
res = math.ceil(MIN / X) * X
print(res)

Output
10043

Explanation:

  • math.ceil(MIN / X) finds the smallest integer greater than or equal to MIN / X.
  • Multiplying this by X gives the next multiple of X that is ≥ MIN.

Using Mathematical Formula

In this method, we directly calculate the smallest K-digit number (10 ^ (K-1)) and then find the next multiple of X that is greater than or equal to it.

Python
import math
X, K = 83, 5
MIN = 10 ** (K - 1)

if MIN % X == 0:
    res = MIN
else:
    res = ((MIN + X) - ((MIN + X) % X))

print(res)

Output
10043

Explanation:

  • 10 ** (K - 1) gives the smallest K-digit number.
  • If it’s already divisible by X, that’s our answer.
  • Otherwise, we add X and subtract the remainder (MIN + X) % X to reach the next multiple of X.
  • The logic ensures we get the smallest number divisible by X within the K-digit range.

Using While Loop

This approach iteratively checks numbers starting from the smallest K-digit number until it finds one divisible by X. It’s simple but less efficient for large inputs.

Python
X, K = 83, 5
num = 10 ** (K - 1)
while num % X != 0:
    num += 1

print(num)

Output
10043

Explanation:

  • Start from the smallest K-digit number.
  • Keep incrementing by 1 until the number becomes divisible by X.
  • The loop stops once num % X == 0.

Using List Comprehension

Although not practical for large inputs, this method shows how list comprehension can find the first K-digit number divisible by X quickly for small ranges.

Python
X, K = 83, 5
nums = [i for i in range(10 ** (K - 1), 10 ** K) if i % X == 0]
print(nums[0])

Output
10043

Explanation:

  • "range(10 ** (K - 1), 10 ** K)" generates all K-digit numbers (from the smallest to the largest).
  • The list comprehension filters this range and keeps only numbers divisible by X (i % X == 0).
  • nums[0] accesses the first K-digit number that is divisible by X.

Please refer complete article on Smallest K digit number divisible by X for more details!


Article Tags :

Explore