
Ninja’s friend challenged him with an interesting problem to test his intelligence. His friend gives him the number ‘N’, Ninja’s task is to find the smallest number ‘X’ such that the product of the digits of ‘X’ is equal to ‘N’.Can you help Ninja to solve this problem?
You are given a number ‘N’, you have to find the minimum number ‘X’ such that the product of the digits of ‘X’ is equal to ‘N’.If no such number is found, print -1.
For ExampleIf the given number is 36, the smallest number will be 49 as the product of digits is 36 (=4*9).
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ denoting the given number.
Output Format:
For each test case, print an integer corresponding to the minimum number ‘X’ such that the product of the digits of ‘X’ is equal to ‘N’.
Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6.
Time limit: 1 sec
2
36
42
49
67
For the first test case,
The smallest number is 36 as the product of 4 and 9 is 36.
Hence, the answer is 49.
For the second test case:
The smallest number is 67 as the product of 4 and 9 is 42.
Hence, the answer is 67.
2
10
21
25
37
Try all numbers till be smallest number is found.
In this approach, we will find the factors of ‘N’ as, we know the digits can be between 1 to 9, so if we found a prime factor greater than 9, the answer is not possible. After assuring that the answer is possible, we will try every number from 1 and check its digit product using the function HELPER(X) which will return the product of digits of ‘X’.So, we will return the minimum ‘X’ for which HELPER(X) is equal to ‘N’.
Algorithm:
O(MAX_ANS * log10(MAX_ANS)), where ‘MAX_ANS’ is the greatest answer possible.
In this approach, we are trying each number till the answer is not found, and for each try, we are traversing its all digits, which takes O(log10X) time. So, in the worst case, the total time is MAX_ANS * log10(MAX_ANS). Hence, the overall time complexity is O(MAX_ANS * log10(MAX_ANS)).
O(1)
In this approach, we are using constant space. Hence, the overall space complexity is O(1).