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”.
Examples:
Input : 100
Output : 455
Explanation: 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.
C++
#include <bits/stdc++.h>
using namespace std;
long long int smallestNumber( int n)
{
if (n >= 0 && n <= 9)
return n;
stack< int > digits;
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 long int k = 0;
while (!digits.empty())
{
k = k*10 + digits.top();
digits.pop();
}
return k;
}
int main()
{
int n = 100;
cout << smallestNumber(n);
return 0;
}
|
Java
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));
}
}
|
Python3
import math as mt
def smallestNumber(n):
if (n > = 0 and n < = 9 ):
return n
digits = list ()
for i in range ( 9 , 1 , - 1 ):
while (n % i = = 0 ):
digits.append(i)
n = n / / i
if (n ! = 1 ):
return - 1
k = 0
while ( len (digits) ! = 0 ):
k = k * 10 + digits[ - 1 ]
digits.pop()
return k
n = 100
print (smallestNumber(n))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static long smallestNumber( int n) {
if (n >= 0 && n <= 9) {
return n;
}
Stack< int > digits = new Stack< int >();
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.Count!=0) {
k = k * 10 + digits.Peek();
digits.Pop();
}
return k;
}
static public void Main() {
int n = 100;
Console.Write(smallestNumber(n));
}
}
|
PHP
<?php
function smallestNumber( $n )
{
if ( $n >= 0 && $n <= 9)
return $n ;
$digits = array ();
for ( $i = 9; $i >= 2 && $n > 1; $i --)
{
while ( $n % $i == 0)
{
array_push ( $digits , $i );
$n =(int)( $n / $i );
}
}
if ( $n != 1)
return -1;
$k = 0;
while (! empty ( $digits ))
$k = $k * 10 + array_pop ( $digits );
return $k ;
}
$n = 100;
echo smallestNumber( $n );
?>
|
Javascript
<script>
function smallestNumber(n)
{
if (n >= 0 && n <= 9) {
return n;
}
let digits = [];
for (let i = 9; i >= 2 && n > 1; i--) {
while (n % i == 0) {
digits.push(i);
n = Math.floor(n / i);
}
}
if (n != 1) {
return -1;
}
let k = 0;
while (digits.length!=0) {
k = k * 10 + digits[digits.length-1];
digits.pop();
}
return k;
}
let n = 100;
document.write(smallestNumber(n));
</script>
|
Time Complexity: O(log N)
Space Complexity: O(log N)
We can store the required number k in string for large numbers as shown below.
Also, the above approach can be space optimized if we store our answer directly in a string and return the reverse of it as the final answer.
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string getSmallest(ll N) {
string ans;
for ( int i=9;i>=2 && N>1;i--)
{
while (N%i==0)
{
ans.push_back(i+48);
N/=i;
}
}
if (N!=1)
return "-1" ;
else if (ans.length()==0)
return "1" ;
reverse(ans.begin(),ans.end());
return ans;
}
int main()
{
ll N=100;
cout<<getSmallest(N);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String getSmallest( long N) {
String ans = "" ;
for ( int i = 9 ; i >= 2 && N > 1 ; i--) {
while (N % i == 0 ) {
ans += ( char )(i + '0' );
N /= i;
}
}
if (N != 1 ) {
return "-1" ;
} else if (ans.length() == 0 ) {
return "1" ;
}
return new StringBuilder(ans).reverse().toString();
}
public static void main(String[] args) {
long N = 100 ;
System.out.println(getSmallest(N));
}
}
|
Python3
def getSmallest(N):
ans = ""
for i in range ( 9 , 1 , - 1 ):
while N > 1 and N % i = = 0 :
ans + = str (i)
N / / = i
if N ! = 1 :
return "-1"
elif len (ans) = = 0 :
return "1"
return ans[:: - 1 ]
if __name__ = = '__main__' :
N = 100
print (getSmallest(N))
|
C#
using System;
public class Program
{
static string GetSmallest( int N)
{
string ans = "" ;
for ( int i = 9; i > 1; i--)
{
while (N > 1 && N % i == 0)
{
ans += i.ToString();
N /= i;
}
}
if (N != 1)
{
return "-1" ;
}
else if (ans.Length == 0)
{
return "1" ;
}
char [] charArray = ans.ToCharArray();
Array.Reverse(charArray);
return new string (charArray);
}
public static void Main()
{
int N = 100;
Console.WriteLine(GetSmallest(N));
}
}
|
Javascript
function getSmallest(N) {
let ans = "" ;
for (let i = 9; i > 1; i--) {
while (N > 1 && N % i === 0) {
ans += i.toString();
N /= i;
}
}
if (N !== 1) {
return "-1" ;
} else if (ans.length === 0) {
return "1" ;
}
return ans.split( "" ).reverse().join( "" );
}
const N = 100;
console.log(getSmallest(N));
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
28 Mar, 2023
Like Article
Save Article