UVA 993 Product of digits Solution
Smallest number k such that the product of digits of k is equal to n
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”.
Solution in c++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#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,t,l ;
cin>>t;
while(t--)
{
cin>>n;
cout << smallestNumber(n)<<endl;
}
return 0;
}
No comments