Given a non-negative number n. The problem is to find the smallest number k such that the product of digits of k is equal to n. If no such number k can be formed then print “-1”.
Input : 100 Output : 455 4*5*5 = 100 and 455 is the smallest possible number. Input : 26 Output : -1
Source: Asked in Amazon Interview
Approach: For each i = 9 to 2, repeatedly divide n by i until it cannot be further divided or the list of numbers from 9 to 2 gets finished. Also, in the process of division push each digit i onto the stack which divides n completely. After the above process gets completed check whether n == 1 or not. If not, then print “-1”, else form the number k using the digits from the stack containing the digits in the same sequence as popped from the stack.
Time Complexity: O(num), where num is the size of the stack.
Space Complexity: O(num), where num is the size of the stack.
We can store the required number k in string for large numbers.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if product of digits of a number at even and odd places is equal
- Find maximum product of digits among numbers less than or equal to N
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Smallest number with given sum of digits and sum of square of digits
- Find smallest number with given number of digits and sum of digits
- Smallest even digits number not less than N
- Smallest odd number with N digits
- Smallest Even number with N digits
- Smallest odd digits number not less than N
- Number of digits in the product of two numbers
- Count number of triplets with product equal to given number with duplicates allowed
- Smallest number with sum of digits as N and divisible by 10^N
- Find the kth smallest number with sum of digits as m
- Smallest number with at least n digits in factorial
- Find the smallest number whose digits multiply to a given number n