Python Program for Smallest K Digit Number Divisible by X (original) (raw)

Last Updated : 14 Nov, 2025

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)

`

**Explanation:

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)

`

**Explanation:

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)

`

**Explanation:

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])

`

**Explanation:

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