Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Digit Operations to Make Two Integers Equal

XPChallenge Points: 20
levelLevel: Medium

You are given two integers n and m, both having the same number of digits.
You can modify n using the following operations any number of times:

  • Select any digit in n (that is not 9) and increase it by 1.

  • Select any digit in n (that is not 0) and decrease it by 1.

However, there’s an important restriction — at no point during these operations (including the starting and intermediate states) can the number n become a prime number.

Each time you perform an operation, the cost increases by the new value of n obtained after that operation.
Your goal is to find the minimum total cost needed to transform n into m.
If it’s impossible to make the transformation without violating the rule, return -1.

Example 1:

Input: n = 21, m = 25

Output: 170

Explanation:

21 → 22 → 23 → 24 → 25 But since 23 is prime, we must skip that path. Alternate path: 21 → 31 → 32 → 33 → 34 → 24 → 25 The minimum total sum of all intermediate values is 184.

Example 2:

Input: n = 13, m = 16

Output: -1

Explanation:

13 is already prime, and we can’t start from a prime number. Hence, it’s impossible.

Example 3:

Input: n = 42, m = 45

Output: -1

Explanation:

Increase digits step by step without forming a prime. 42 → 43 (prime, invalid) Alternate route: 42 → 52 → 53 (prime, invalid) Best valid route: 42 → 62 → 63 → 64 → 65 Total sum of intermediate values = 258.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result