Smallest number k such that the product of digits of k is equal to n | Java implementation to find smallest number k such that the product of digits of k is equal to n ; function to find smallest number k such that the product of digits of k is equal to n ; if ' n ' is a single digit number , then it is the required number ; stack the store the digits ; repeatedly divide ' n ' by the numbers from 9 to 2 until all the numbers are used or ' n ' > 1 ; save the digit ' i ' that divides ' n ' onto the stack ; if true , then no number ' k ' can be formed ; pop digits from the stack ' digits ' and add them to ' k ' ; required smallest number ; Driver program to test above
import java . util . Stack ; public class GFG { static long smallestNumber ( int n ) { if ( n >= 0 && n <= 9 ) { return n ; } Stack < Integer > digits = new Stack < > ( ) ; for ( int i = 9 ; i >= 2 && n > 1 ; i -- ) { while ( n % i == 0 ) { digits . push ( i ) ; n = n / i ; } } if ( n != 1 ) { return - 1 ; } long k = 0 ; while ( ! digits . empty ( ) ) { k = k * 10 + digits . peek ( ) ; digits . pop ( ) ; } return k ; } static public void main ( String [ ] args ) { int n = 100 ; System . out . println ( smallestNumber ( n ) ) ; } }