You are given a positive integer βNβ. The task is to find and return the smallest number, βMβ, such that the multiplication of all the digits in βMβ is equal to βNβ. If no such βMβ is possible or βMβ cannot fit in a 32-bit signed integer, return 0.
Example:βNβ = 90
Possible values for βMβ are:
1. 259 (2*5*9 = 90)
2. 3352 (3*3*5*2 = 90)
3. 2335 (2*3*3*5 = 90)
4. 952 (9*5*2 = 90), and so on.
Here, β259β is the smallest possible βMβ. Thus, you should return β259β as the answer.
The first line of input contains an integer βTβ which denotes the number of test cases. Then, the βTβ test cases follow.
The first and only line of each test case contains an integer βNβ, i.e., the given integer.
Output format:
For every test case, return the smallest possible βMβ value. If no such βMβ is possible or βMβ cannot fit in a 32-bit signed integer, return 0.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 1000
1 <= N <= 10^9
Time limit: 1 sec
2
120
62
358
0
Test Case 1:
Possible values for βMβ are:
1. 358 (3*5*8 = 120)
2. 2345 (2*3*4*5 = 120)
3. 22235 (2*2*2*3*5 = 120), and so on.
Here, β358β is the smallest possible βMβ. Thus, you should return β358β as the answer.
Test Case 2:
The factorization of β62 = 2*31β. As β31β is a prime number, it cannot have single-digit factors (β0β to β9β) . Thus, itβs impossible to have an integer βMβ, such that the multiplication of its digits is equal to β62β. You should return β0β as the answer.
2
168
180
378
459
Check for all possible βMβ values.
A simple approach will be to iterate through all possible βMβ values, i.e., from β1β to β2147483647β (the largest value that a signed 32-bit integer field can hold), and check if their digit multiplication is equal to βNβ.
Algorithm:
O(M*log(M)), where βMβ is the answer.
We iterate through all the integers up to βMβ or β2147483647β (when βNβ has a prime factor greater than β9β), and in each iteration, we compute the digit multiplication of the current βMβ in βO(log(M))β. Thus, the time complexity is βO(M*log(M))β.
O(1).
Since we are not using any extra space, space complexity is constant.