Find a number K such that product of digits of K must be equal to N. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Monday 22 July 2019

Find a number K such that product of digits of K must be equal to N.


Given a number N. Find a number K such that product of digits of K must be equal to N.
Note: K must be as small as possible.
Input: First line of input contains the number of test cases T. For each test case, there will be a single line containing N.
Output: For each test case, output single integer. If K is not possible, print "-1" (without quotes).


  • 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 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.


You can avoid the use of stack by incrementally build the number.
int rad= 0;
int res= 0;
for (int i=9; i>=2 && n > 1; i--)
{
while (n % i == 0)
{
result = pow(10, rad)*i+res;
rad++;
n = n / i;
}


#include <bits/stdc++.h>
using namespace std;
long long game(long long n){
     stack<int> v;
 
 
    if( n>=0&&n<=9){
        return n;
    }
 
    for(int i=9;i>=2&&n>1;i--){
            while(n%i==0){
               v.push(i);
                 n/=i;
            }
    }
 
    if(n!=1)
    return -1;
     long long p=0;
    while(!v.empty()){
        p=p*10+v.top();
        v.pop();
    }
 
    return p;
}
int main() {
//code
int t;
cin>>t;
while(t--){
    long long  n;
    cin>>n;
    cout<<game(n)<<endl;

}
return 0;
}