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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Smallest number greater than Y with sum of digits equal to X
- Smallest number greater than or equal to N using only digits 1 to K
- Smallest number greater than or equal to X whose sum of digits is divisible by Y
- 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
- Find smallest number with given number of digits and sum of digits under given constraints
- 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 odd number with N digits
- Smallest Even number with N digits
- Smallest odd digits number not less than N
- Smallest even digits number not less than N
- Find smallest number formed by inverting digits of given number N
- Find smallest possible Number from a given large Number with same count of digits
- Find the kth smallest number with sum of digits as m
- Smallest number whose sum of digits is square of N
- Find the smallest number whose sum of digits is N
- Smallest number with at least n digits in factorial
- Smallest number whose square has N digits